Arithmetic type issues

Similar documents
Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Computer System and programming in C

Lecture 3. More About C

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Programming in C++ 5. Integral data types

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

LECTURE 3 C++ Basics Part 2

Programming for Engineers: Operators, Expressions, and Statem

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Chapter 3. Section 3.10 Type of Expressions and Automatic Conversion. CS 50 Hathairat Rattanasook

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Operators and Expressions:

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS61B Lecture #14: Integers. Last modified: Wed Sep 27 15:44: CS61B: Lecture #14 1

Unit 3. Operators. School of Science and Technology INTRODUCTION

1.3b Type Conversion

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

Chapter 3: Operators, Expressions and Type Conversion

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

Operators & Expressions

Add Subtract Multiply Divide

Operators. Lecture 3 COP 3014 Spring January 16, 2018

ISA 563 : Fundamentals of Systems Programming

Lecture 12 Integers. Computer and Network Security 19th of December Computer Science and Engineering Department

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Basic Assignment and Arithmetic Operators

Programming and Data Structures

Informatics Ingeniería en Electrónica y Automática Industrial

Expressions and Casting

Binary Representations and Arithmetic

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Arithmetic Operators. Portability: Printing Numbers

CMSC 104 -Lecture 6 John Y. Park, adapted by C Grasso

Chapter 2. Elementary Programming

CS61B Lecture #14: Integers

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Operators in C. Staff Incharge: S.Sasirekha

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Information Science 1

Chapter 7. Basic Types

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

CS102: Variables and Expressions

Chapter 2: Using Data

C: How to Program. Week /Mar/05

Main Memory Organization

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Fixed-Point Math and Other Optimizations

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Information Science 1

MA 511: Computer Programming Lecture 2: Partha Sarathi Mandal

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Data Types and Variables in C language

Fundamental of Programming (C)

(2-1) Numeric Expressions in C H&K Chapter 2. Instructor - Andrew S. O Fallon CptS 121 (August 27, 2018) Washington State University

CEN 414 Java Programming

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

QUIZ: What value is stored in a after this

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

Chapter 1 & 2 Introduction to C Language

Declaration and Memory

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Bits and Bytes. Data Representation. A binary digit or bit has a value of either 0 or 1; these are the values we can store in hardware devices.

Fundamentals of Programming

Chapter 3. Fundamental Data Types

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

3.5 Floating Point: Overview

Reserved Words and Identifiers

ITP 342 Mobile App Dev. Code

ECE 122 Engineering Problem Solving with Java

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

C Programming Basics

Programming for Engineers Introduction to C

CS 31: Intro to Systems Binary Arithmetic. Martin Gagné Swarthmore College January 24, 2016

CpSc 111 Lab 3 Integer Variables, Mathematical Operations, & Redirection

Lecture 4 CSE July 1992

REVIEW. The C++ Programming Language. CS 151 Review #2

EXPRESSIONS AND ASSIGNMENT CITS1001

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C

CS Programming In C

Control Flow, Functions and Basic Linkage

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expression and Operator

Binghamton University. CS-211 Fall Data Conversion. software diversity in action

AGENDA Binary Operations CS 3330 Samira Khan

Bits, Bytes, and Integers

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions

Transcription:

Arithmetic type issues Type combination and promotion ( a 32) = 97 32 = 65 = A Smaller type (char) is promoted to be the same size as the larger type (int) Determined at compile time - based purely on the types of the values in the expressions Does not lose information convert from type to compatible large type

Arithmetic operators Mathematical Symbols + - * / % addition, subtraction, multiplication, division, modulus Works for both int and float + - * / / operator performs integer division if both operands are integer i.e. truncates; otherwise, float % operator divides two integer operands with an integer result of the remainder Precedence left to right () always first * / % + -

Arithmetic type conversions Usual Arithmetic Conversions Many operators cause conversions and yield result types in a similar way. The effect is to bring operands into a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions. If either operand is long double, the other is converted to long double. If either operand is double, the other is converted to double. If either operand is float, the other is converted to float. Otherwise, the integral promotions are performed on both operands; If either operand is unsigned long int, the other is converted to unsigned long int. If one operand is long int and the other is unsigned int, the effect depends on whether a long int can represent all values of an unsigned int; if so, the unsigned int operand is converted to long int; if not, both are converted to unsigned long int. If one operand is long int, the other is converted to long int. If either operand is unsigned int, the other is converted to unsigned int. Otherwise, both operands have type int. NOTE: There are two changes here. First, arithmetic on float operands may be done in single precision, rather than double; the first edition specified that all floating arithmetic was double precision. Second, shorter unsigned types, when combined with a larger signed type, do not propagate the unsigned property to the result type; in the first edition, the unsigned always dominated. The new rules are slightly more complicated, but reduce somewhat the surprises that may occur when an unsigned quantity meets signed. Unexpected results may still occur when an unsigned expression is compared to a signed expression of the same size.

Arithmetic Expressions A bug s life Pitfall -- int Overflow I once had a piece of code which tried to compute the number of bytes in a buffer with the expression (k * 1024) where k was an int representing the number of kilobytes I wanted. Unfortunately this was on a machine where int happened to be 16 bits. Since k and 1024 were both int, there was no promotion. For values of k >= 32, the product was too big to fit in the 16 bit int resulting in an overflow. The compiler can do whatever it wants in overflow situations -- typically the high order bits just vanish. One way to fix the code was to rewrite it as (k * 1024L) -- the long constant forced the promotion of the int. This was not a fun bug to track down -- the expression sure looked reasonable in the source code. Only stepping past the key line in the debugger showed the overflow problem. "Professional Programmer's Language." This example also demonstrates the way that C only promotes based on the types in an expression. The compiler does not consider the values 32 or 1024 to realize that the operation will overflow (in general, the values don't exist until run time anyway). The compiler just looks at the compile time types, int and int in this case, and thinks everything is fine.

Arithmetic expressions - Truncation Pitfall -- int vs. float Arithmetic Here's an example of the sort of code where int vs. float arithmetic can cause problems. Suppose the following code is supposed to scale a homework score in the range 0..20 to be in the range 0..100. { int score;...// suppose score gets set in the range 0..20 somehow 7 score = (score / 20) * 100; // NO -- score/20 truncates to 0... Unfortunately, score will almost always be set to 0 for this code because the integer division in the expression (score/20) will be 0 for every value of score less than 20. The fix is to force the quotient to be computed as a floating point number... score = ((double)score / 20) * 100; // OK -- floating point division from cast score = (score / 20.0) * 100; // OK -- floating point division from 20.0 score = (int)(score / 20.0) * 100; // NO -- the (int) truncates the floating // quotient back to 0

Example #include <stdio.h> int main() { int first, second, add; float divide; printf("enter two integers\n"); scanf("%d %d", &first, &second); add = first + second; divide = first / (float)second; printf("sum = %d\n",add); printf("division = %.2f\n",divide); Variables Function calls Input Output Operators Typecasting } return 0;

Relational Operators Used to compare two values < <= > >= ==!= Precedence order given above; then left to right else equivalences (respectively) >= > <= <!= == Arithmetic operators have higher precedence than relational operators A true statement is one that evaluates to a nonzero number. A false statement evaluates to zero. When you perform comparison with the relational operators, the operator will return 1 if the comparison is true, or 0 if the comparison is false. For example, the check 0 == 2 evaluates to 0. The check 2 == 2 evaluates to a 1. TRY: printf( %d,2==1);

Example #include <stdio.h> /* print Fahrenheit-Celsius table for fahr = 0, 20,..., 300 where the conversion factor is C = (5/9) x (F-32) */ main() { int fahr, celsius; int lower, upper, step; lower = 0; /* lower limit of temperature scale */ upper = 300; /* upper limit */ step = 20; /* step size */ fahr = lower; while (fahr <= upper) { celsius = 5 * (fahr-32) / 9; // problem? 9.0? Typecast? printf("%d\t%d\n", fahr, celsius); fahr = fahr + step; } return 0; }