CSE 1001 Fundamentals of Software Development 1 Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018
Identifiers, Variables and Data Types Reserved Words Identifiers in C Variables and Values Data Types and Literals in C Assignment Statements and Compatibilities Type Casting Arithmetic Operators and Expressions Reading: Textbook, Chapter 2 (p. 50-61, p. 76-85)
Reserved Words A reserved word in a programming language is one with special meaning library names, variable types, flow of control statements See Appendix E in the textbook (8 th Ed.) for a list of C's reserved words They should not be used for other purposes because their meaning is well-known to all who know the language cannot be redefined in code Examples: int, void, main, return
Identifiers Standard Identifiers: also have special meaning, just like reserved words e.g., names of operations or functions in libraries printf, scanf, etc. can be redefined in code -- be careful! User-Defined Identifiers created and used by programmers to name memory locations (e.g., variable names, constants) Both types can be arbitrarily long, but some compilers don't consider two identifiers different unless they vary within the first 31 characters
C Identifier Naming Identifiers may contain only the following: Letters Digits (0 through 9) The underscore character (_) The first character cannot be a digit reserved words may not be used as identifiers Don't redefine standard identifiers this will compile and run, but is bad practice
C Identifiers Legal or not? i Counter tree include great1 cow_barn cow-barn 7th-variable _width myvalue My_Value start date!6
C Identifiers Identifiers can be arbitrarily long: int myidentifierisreallyreallyreallylongfornoreason; Some compilers do not consider two identifiers to be different unless they vary somewhere within the first 31 characters. Thus, the following two identifiers might be considered the same: myidentifierisreallyreallyreallylongfornoreason1 myidentifierisreallyreallyreallylongfornoreason2 C is case sensitive: counter, Counter and COUNTER are all different identifiers!7
C Identifiers Important to distinguish between rules of the language and naming conventions Rules of the language (syntax): enforced by the compiler Naming conventions: commonly used guidelines that are typically a matter of style, but not enforced by the compiler!8
Naming Conventions Choose names that are (human) readable and meaningful, such as count or width (rather than c or w) Makes it easier to follow the code and remember what variable to use later in your code Short names are sometimes okay: Counters: i,j,k Math equations: x,y,z Variables: Begin with a lowercase letter e.g., grades, bank_balance Multi-word names use underscores between words e.g., class_average!9
Variables and Values Variables are memory locations that store data (e.g., numbers, letters, etc.) The data stored by a variable is called its value The value of a variable can be changed Variables must be declared before they can be used Declaration tells the compiler the variable names and the type of information they will store (e.g., the data type) double myname; variable data type int counter; variable name!10
Variables and Values #include <stdio.h> Output: If you have 6 cows per barn int main(void) { int barns, cowsper, totalcows; barns = 10; cowsper = 6; totalcows = barns * cowsper; and 10 barns, then the total number of cows is 60 variable declarations variable initialization/assignment } printf("if you have %d cows per barn \n", cowsper); printf("and %d barns, then\n", barns); printf("the total number of cows is %d.\n", totalcows); return 0;!11
Variables and Values Variables: b a r n s c o w s P e r t o t a l C o w s When you declare a variable, you provide its name and type: int barns, cowsper, totalcows; Can be declared separately: i n t barns; i n t cowsper; i n t totalcows; Assigning values (variable must be declared before use) barns = 10; cowsper = 6; totalcows = barns * cowsper;!12
Syntax and Examples A variable s type determines what kind of value it can store (e.g., real numbers, characters, integers, etc.) Examples: int x, y, i, j; double balance, interestrate; char jointorindividual; A variable is typically declared at the beginning of main: int main(void) { -- declare variables here : } Variables must be declared and initialized before they are used!13
Types in C In most programming languages, a type implies several things: A set of possible values A (hardware) representation for those values A set of operations on those values Example: type int Values: 2 bytes: integers in the range -32,768 to 32,767 4 bytes: -2,147,483,648 to 2,147,483,647 Representation: 2 or 4 bytes, binary Operations: addition (+), subtraction (-), multiplication (*), division (/), and remainder (%)!14
Data Types in C Primitive types (a.k.a. standard types): Values are simple, non-decomposable values such as a number (not a digit) or character can be variables or constants each primitive type has a set range of values it may represent used as abstractions for data: int represents whole numbers double represents real numbers (decimals) char represents a single character void represents and empty set (e.g., it stores null)!15
Examples of Primitive Values Integer values: 0-1 365 12000 Floating point values: 0.99-22.8 3.1415 5.0 4.83e-2 0.25e5 Character values (enclosed in single quotes): a A % Values such as the above are often referred to as constants or literals!16
More Primitive Types Integer types: int (arguably the most commonly used) Two floating-point types: float double (again, arguably the most common) One character type: char
Data Type Qualifiers Data type qualifiers are used with primitive types to alter their range (e.g., the numbers or characters they can represent) and storage space requirements C data type qualifiers (not used for floats): signed unsigned Thus, we can declare a signed int or an unsigned int
Integer Data Types C Integer Data Types Memory Used Size Range * short 2 bytes -32,768 to 32,767 signed short 2 bytes -32,768 to 32,767 unsigned short 2 bytes 0 to 65,535 int 4 bytes -2,147,483,648 to 2,147,483,647 signed int 4 bytes -2,147,483,648 to 2,147,483,647 unsigned int 4 bytes 0 to 4,294,967,295 long signed long 8 bytes 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 unsigned long 8 bytes 0 to <a really big number> * These are HIGHLY dependent on the compiler and processor used.!19
Floating Point Data Types C Floating Point Data Types Memory Used Size Range float 4 bytes 3.4E-37 to 3.4E+38 double 8 bytes 1.7E-307 to 1.7E+308 long double 10 bytes 3.4E-4931 to 1.1E+4932!20
Why Different Types of Numbers? Operations can be faster using integers rather than doubles Some types use less memory, which may be important in large or complex programs Rounding errors may occur if the wrong data type is used (e.g., using an int when you need a double)
Character Data Types C Character Data Types Memory Used Size Range char 1 byte -128 to 127 signed char 1 byte -128 to 127 unsigned char 1 byte 0 to 255 chars are represented as integers through the use of the ASCII character set not useful for languages that use alternative alphabets see http://www.asciitable.com/!22
Literals Values such as 2, 3.7 or 'y' are called constants or literals Integer literals can be preceded by a + or sign, but cannot contain commas Every integer literal is of type int (or one of its qualified variants such as short int) The type of an integer literal can be determined by inspection (e.g., by looking at it!)!23
Floating Point Literals Floating point literals can also be preceded by a + or sign, but cannot contain commas There are two distinct properties that every floating point literal has: format: either fully expanded notation or scientific notation type: either float, double, or long double Both the format and the type of a floating point literal can be determined by inspection (i.e., by looking at it)!24
Assignment Statements An assignment statement is used to assign a value to a variable int answer; answer = 42; variable declaration assignment statement The equals sign (=) is called the assignment operator Before assignment: After assignment: barns?? barns 10 cowsper?? cowsper 6 * totalcows?? totalcows 60!25
Expression Data Types The data type of an arithmetic expression depends on the data types of the operands length * width; The result of this expression will be of type: int if both length and width are of type int double if either length or width are of type double mixed-type expression: an expression with operands of more than one data type
Assignment Statements Assignment syntax: variable = expression; expression Can Be Example A literal or constant x = 4.3 Another variable An expression that combines variables and literals using operators x = y x = y + 4.3 / 10!27
Assignment Compatibilities C is statically typed, which means that there are limitations on mixing variables and values in expressions and assignments int x = 0; long y = 0; double z = 0.0; x = y; /* "legal", but not recommended (overflow) */ x = z; /* "legal", but type converted from float to int) */ y = z; /* "legal", but type converted from float to int) */ z = 3.6; /* legal since 3.6 is by default a double */ y = 25; /* legal, but why? */!28
Type Casting (a.k.a Type Conversion) A type cast creates a value of a new type from an original type A type cast can be used to force an assignment when otherwise it would be illegal or auto-cast by the compiler Example: double distance; distance = 9.0; int points; points = distance; // legal, but will be (auto) cast to an int points = (int)distance; // legal, specifies cast explicitly!29
Type Casting The value of (int)distance is 9, but the value of distance both before and after the cast is 9.0 The type of distance does NOT change and remains double What happens if distance contains 9.7? any value to the right of the decimal point is truncated (as opposed to rounded) Remember to cast with care because the results can be unpredictable int x; long z = 5000000000000000009; x = (int)z;!30
Arithmetic Expressions Much the same as what you learned in math classes, but more precise in expression Rules of operator precedence follow math rules (BEDMAS, PEMDAS, etc.) Assume a = 10 and c = 2. What are the results of the following calculations? b = 4 * a / c - 3 b = (4 * a) / c - 3 b = 4 * a / (c - 3) b = 4 * (a / c) - 3
Arithmetic Operators Operator Meaning Examples + addition - subtraction * multiplication / division % modulus (remainder) 6.0 + 4.0 is 10.0 6 + 4 is 10 6.0-4.0 is 2.0 6-4 is 2 6.0 * 4.0 is 24.0 6 * 4 is 24 6.0 / 4.0 is 1.5 6 / 4 is 1 6 % 2 is 0 7 % 2 is 1
Arithmetic Operators Operators have operands, which are literals, variables or sub-expressions Expressions with two or more operators can be viewed as a series of steps, each involving only two operands The result of one step produces an operand that is used in the next step Most of the basic math rules of precedence apply C is left-associative for arithmetic operations
Arithmetic Operations Example: int x = 0, y = 50, z = 20; double balance = 50.25, rate = 0.05; x = x + y + z; balance = balance + balance * rate; balance = (balance + balance) * rate;!34
Expression Type A single expression can contain operands of both double and int types In that case, the type of the resulting expression is double int hoursworked = 40; double payrate = 8.25; double totalpay; Then the expression in the assignment: totalpay = hoursworked * payrate; results in a double with a value of 330.0 If the variable totalpay is of type int, then the above statement results in an int with value 330. Why?!35
The Division Operator The division operator ( / ) behaves as expected If at least one of the operands is of type double, then the result is also of type double: 9.0 / 2 = 4.5 9 / 2.0 = 4.5 9.0 / 2.0 = 4.5 10.0 / 2 = 5.0 If both operands are of type int, then the result is truncated (not rounded) and of type int: 9 / 2 = 4 99 / 100 = 0!36
The Division Operator The rules on the previous slide are true regardless of whether the operands are literals, variables, or more general expressions int x = 40; int y = 7; double z = 8.25; double w = 2.5; If at least one of the operands is of type double, then the result is also of type double: z / x = 0.20625 y / 2.5 = 2.8 y / w = 2.8 (y + 1) / w = 3.2 If both operands are of type int, then the result is truncated (not rounded) and of type int: x / y = 5 (x + 1) / 8 = 5 x / 7 = 5!37
The mod Operator The mod ( % ) operator is used with operands of integer type to obtain the remainder after integer division 14 divided by 4 is 3 with a remainder of 2: In other words: 14 % 4 is equal to 2 The mod operator has many uses, including determining: If an integer is odd or even: x % 2 = 0 If one integer is evenly divisible by another integer: a % b = 0 Mapping a large number of m items, number 1 through m, into n>=2 groups or buckets!38
Unary Operators A unary operator takes only one operand C is right-associative for unary operators Operand Meaning Example! Logical Negation - Unary Minus -4 + Unary Plus +4!1 = 0!0 = 1 ++<variable> pre-increment ++x <variable>++ post-increment x++ --<variable> pre-decrement --x <variable-- post-decrement x--
Operator Precedence Parentheses first, from inside out Operator precedence: unary operators are first (from right to left) *, /, % are second (from left to right) binary + and - are last (from left to right) Use parentheses to force the order you wish to have
Numerical Inaccuracies Representational Error: a.k.a round-off error when a floating point number cannot be represented exactly because a double or float has only a fixed number of decimal places Cancellation Error: when adding very small number to larger numbers, the decimal places may be truncated, thus removing the influence of the small number 10000 + 0.00000005612 = 10000. 00000005612 may be represented as 10000.0 on some computers
Numerical Inaccuracies Arithmetic Underflow: when a value is too small to be represented accurately, it is represented (incorrectly) as 0 Arithmetic Overflow: when a value is too large to be represented accurately has to do with how the number is represented in binary