320 likes | 502 Views
Types, Constants, Operators and Expressions. Introduction. All C programs are made up of functions that perform operations on variables . In this lecture we examine variables Variables are the basic building blocks of a program Variables have: types , names , and constants
E N D
Introduction • All C programs are made up of functions that perform operations on variables. • In this lecture we examine variables • Variables are the basic building blocks of a program • Variables have: types, names, and constants • Operations performed on variables using operators • Each operation forms an expression • A statement is a collection of expressions terminated by ;
The C Type System • C is a “typed” language. • We must explicitly define variables with a specific type. • Different types have different characteristics. • Size: how many bytes of memory a variable occupies. • Representation: what does the bit-pattern mean. • Usage: what operations may be performed a variable. • By specifying types, we enable the compiler to perform a number of tasks for us: • Compiler allocates fixed amount of memory for a given type. • A variable’s type determines what value it can represent and what operations may be performed on it. • Compiler can detect type-mismatch errors.
Variable Names • Names are composed of alphanumeric characters (letters and numbers), and _ (underscore) • Names may not start with a number • Names are case sensitive; eg, step and Step are different variables • Good Style: By convention, variable names begin with a lower-case letter. Short names are given to local variables, while longer more descriptive names to distant variables. Local: step, top, i, j, x, fahr, flag Distant: lookup_table_index, nameListHead
Types • C has three basic data types • Integer types: char, int • Floating point types: float, double • No type (an empty set): void • Different types have different properties: • Values they can represent • Operations that can be performed on them. • These types have finite precision and range. • There is a limit to the size of a number (min, max) • Floating point values have a limit to the number of significant figures. • Size of int may be qualified by long or short
Bits & Bytes • Basic building blocks of digital systems. • 1 Bit = 1 Binary Digit • Stores 1/0, True/False • 1 Byte = 8 Bits
Integer Sizes in ISO C • The standard does not specify exact sizes. The amount of memory storage allocated for a particular type will be different on different systems. • ISO C standard requires only that • char is at least 8 bits • short is at least 16 bits • long is at least 32 bits • short <= int <= long • Range of permissible values of integers is defined in limits.h
Floating-Point Sizes in ISO C • ISO C does not specify the size of floating point types, or even that their sizes are different. • Simply says: float <= double <= long double • Range of permissible values of integers is defined in float.h
More Integer Type Qualifiers signed • explicitly tells the compiler that the quantity is a signed integer (ie, the type may represent a negative number). unsigned • explicitly tells the compiler that the quantity is an unsigned integer (ie, cannot represent a negative number). This doubles the size of the max representable number.
Signed and Unsigned Integers • An integer value is represented by a sequence of bits: base 2 numbers. • For a signed integer, the most-significant-bit (MSB) is the sign bit. • If MSB is 0, the number is positive. If 1, the number is negative (using a 2’s complement binary representation). • An unsigned integer does not have a sign bit, and the MSB is part of the actual number – extending the maximum possible value by a factor of 2. Examples for 8-bit integers: 00000111 -> 7 (signed or unsigned) 10000111 -> -121 (signed, 2’s complement) 10000111 -> 135 (unsigned)
Value Ranges for Typical Sizes • signed char, -128 to 127, (-27 to 27 – 1) • unsigned char, 0 to 255, (28 – 1) • signed short, -32768 to 32767, (-215 to 215 – 1) • unsigned short, 0 to 65535, (216 – 1) • int, -2,147,483,648 to 2,147,483,647, (-231 to 231 - 1) • unsigned, 0 to 4,294,967,296, (232 - 1) • float, 1.2e-38 to 3.4e+38, (6 decimal digits precision) • double, 2.2e-308 to 1.8e+308, (15 decimal digits precision) • All are available in limit.h and float.h
More Type Qualifiers const • indicates that a variable is intended to remain constant and should not be changed. const int DoesNotChange = 5; DoesNotChange = 6; /* will not compile */
Integer Constants • There are many ways to represent the same integer value • Decimal, 12 • Octal, 014 • Hexadecimal, 0x0C • All represent the same binary value, 00001100 • Consider the following 8-bit binary number binary: 0110 1010 decimal: 2+8+32+64 = 106 hex:6 and 10 = 0x6A • a long constant is written like 1234567890L or 1234567890l • for an unsigned integer, add the suffix U or u • for an unsigned long integer, add the suffix UL or ul
Floating Point Constants • Specify by a decimal point and/or e or E 3.14159 3. -.001 2.25e-3 • Are type double by default • Can specify type float by appending an f 12.5f 7.F
Representing Characters:American Standard Code for Information Interchange • All data is stored as sets of bits. • 2 main questions: • How do we represent letters? • Convert to a number: e.g. ‘A’ = 1; ‘B’ = 2 etc. • How do we communicate between different systems? • Use a standard conversion table.
ASCII • Standard method for representing characters as integers.
Character Constants • Character constants are simply integers • To represent characters, C uses a lookup table • Each character has a unique integer code • ASCII table is most common code • Eg., Letter “R” we can represent by • Its ASCII integer code: 82 or 0122 or 0x52 • Or, use character constant:‘R’ • The type of ‘R’ is an int not a char • Some ASCII constants are defined as escape sequences (for characters that are difficult or impossible to type) \n new line \t tab \b backspace \0 NUL character
String Constants • A string is a sequence of chars terminated by a NUL character, ‘\0’. • A string constant is written as e.g. “this is a string” • A string constant is automatically terminated by a NUL e.g. |t|h|i|s| |i|s| |a| |s|t|r|i|n|g|\0| WARNING! • Don’t confuse a character constant ‘X’ which is an int with a (null-terminated) string constant “X” which is an array of two chars: |X|\0| • Thus, sizeof(‘X’) is 4 (for Win32) and sizeof(“X”) is 2
Aside: printf format specifiers • In printf(), use conversion specifiers, prefixed by % %c character - char %d decimal int %x hexadecimal int %o octal int %f %e %g float %f %e %g double • Conversion specifiers MUST match the type of the variable it corresponds to, else the program will be incorrect.
Example: ASCIITbl.c • See Text Section 2.5 and 13.1 for more information. • Refer to any C textbook for more complete discussion on printf() and its conversion specifiers.
Symbolic Constants • Extremely bad practice to have “magic numbers” in code. It may be difficult to see what the number stands for, and code changes become error-prone. • Use #define to define named constants, all in the one place #define ARRAY_LENGTH 2500 #define BLOCK_SIZE 4096 #define TRACK_SIZE 16*BLOCK_SIZE #define STRING “Hello World!\n” • Symbolic constants mean making changes of constants is easy and safe. • Example: tempf2.c
Arithmetic Operators • Arithmetic operators are + plus - minus * multiply / divide = assignment % modulus (remainder after division) • The first 5 are valid for integer and floating-point types. • The % is valid only for integer types (including char).
Arithmetic Expressions 3.0 / 5.0 – equals 0.6 3 / 5 – integer division truncates, equals 0 17 / 6 – equals 2 18 % 7 - equals 4 2*7 + 5*9 – equals 14 + 45: 59 • Show prime.c
Arithmetic Evaluation • Precedence and order of evaluation. eg, a + b * c • Order of evaluation from left to right. • *, / and % take precedence over + and -, so that a + b * c is the same as a + (b * c) • Precedence table exists, but use brackets () instead for safety!!
Arithmetic Errors • Overflow (integers have finite range) y = x + 1; z = x * y; • Overflow and signed/unsigned • unsigned: modulo wrap around • signed: undefined behaviour • Divide by zero (integers or floats) z = x / y;
Incremental Operators • Increment ++ and decrement-- ++ais equivalent toa = a + 1 • Valid operators on integer or floating-point numbers. • Two forms: preincrement and postincrement int a=2, b, c; b = ++a; /* a=3 and b=3 */ c = a++; /* a=4 and c=3 */
Relational Operators • Relational operators are > greater-than < less-than >= greater-than-or-equal-to <= less-than-or-equal-to == equal-to != not-equal-to • These operators are valid for integer and floating-point types. • Evaluate to 1 if TRUE, and 0 if FALSE 3.2 < 7 equals 1, and x != x equals 0
Logical Operators • Logical operators are && AND || OR ! NOT • && and || connect multiple conditional expressions. • ! negates a conditional expression (non-zero becomes 0, zero becomes 1).
Relational and Logical Expressions int a=1, b=2, c=3, d=3; a < b && b < c && c < d /* FALSE */ a < b && b < c && c <= d /* TRUE */ (a < b && b < c) || c < d /* TRUE */ a && !b /* FALSE */ • Show logical.c and leapyear.c • &&and||are evaluated left-to-right and, once the result of TRUE or FALSE is known, evaluation stops – leaving the remaining expressions unevaluated. This is a useful feature, and leads to several common C idioms. i = 0; while(i < SIZE && array[i] != val) ++i;
Bitwise Operators • Bitwise operators are & bitwise AND | bitwise OR ^ bitwise XOR << left shift >> right shift ~ one’s complement (bitwise NOT) • Used to manipulate individual bits. • Details in later lecture, mention here to avoid confusion with logical operators. They cannot be used interchangeably. • & is not &&, | is not ||, >> is not “much-greater-than”.
Assignment Operators • Assignment operators - for example, a += b; is equivalent to a = a + b; x *= y+1; is equivalent to x = x * (y+1); • Assignment also with other arithmetic operators:+,-,*,/,% • Show factorial.c
Mixed Type Expressions • One can write expressions with variables and constants of different types • The compiler performs implicit conversions on terms so each binary expression has same (larger) type. • (see Section 2.11 of lecture notes for more details) int x = 2, y = 1; float z = 5.4; double a; a = y + x*z; • Type promotion occurs stepwise for each binary expression • (tmp1) = x*z, the variable x is promoted to float; and result stored as a float • (tmp2) = y+(tmp1), the variable y is promoted to float • a = (tmp2), the implicit temporary is promoted to double and result stored in a