460 likes | 615 Views
Chapter 2 Types, Operators, and Expressions. Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University. Introduction. Variables and Constants Basic data objects manipulated in a program Operators
E N D
Chapter 2Types, Operators, and Expressions Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University
Introduction • Variables and Constants • Basic data objects manipulated in a program • Operators • Specify what is to be done to variables and constants • Expressions • Combine variables and constants to produce new values Types, Operators, and Expressions
2.1 Variable Names • Names are made up of letters and digits • The first character must be a letter • The underscore “_” counts as a letter • Improving the readability of long variable names • Don’t begin variable names with underscore • Library routines often use such names • Case sensitive: upper case and lower case letters are distinct • Traditional C practice • Lower case for variable name • Upper case for symbolic constants Types, Operators, and Expressions
2.1 Variable Names • It’s wise to choose variable names that are related to the purpose of the variable. • Keywords are reserved • Usually displayed in blue color Types, Operators, and Expressions
C’s Keywords Types, Operators, and Expressions
Assignment One • Understand the meanings of all C’s keywords • Including their pronunciations • Not how to use them • Submission information • One A4 paper • With your student ID and name • Due date • 2006/09/25 (Mon.) Types, Operators, and Expressions
2.2 Data Types and Sizes • Basic data types • char • A single byte, capable of holding one character in the local character set. • int • An integer, typically reflecting the natural size of integers on the host machine. • float • Single-precision floating point. • double • Double-precision floating point. Types, Operators, and Expressions
2.2 Data Types and Sizes • Qualifiers • short and long apply to integers • short int sh; • long int counter; • int can be omitted, and typically is. • Provide different lengths of integers • short is often 16 bits • long is 32 bits • int is the natural size for a particular machine • either 16 or 32 bits Types, Operators, and Expressions
2.2 Data Types and Sizes • Qualifiers • signed and unsigned apply to char or integers • unsigned : positive or zero • unsigned char : 0 - 255 • signed char : -128 and 127 (in 2’s complement) • Whether plain chars are signed or unsigned is machine-dependent • Printable characters are always positive • float, double and long double • One, two, and three distinct sizes Types, Operators, and Expressions
Exercise 2-1 • Write a program to determine the ranges of char, short, int and long variables, both signed and unsigned, by printing appropriate values from standard headers and by direct manipulation. Harder if your compute them: determine the ranges of various floating-point types. • The standard headers <limits.h> and <float.h> contain symbolic constants for all of these sizes. Types, Operators, and Expressions
2.3 Constants • An integer constant: • 1234 • A long constant is written with l or L: • 123456789L • Unsigned constants are written with a terminal u or U • 123456789UL Types, Operators, and Expressions
2.3 Constants • An integer can be specified in octal or hexadecimal instead of decimal. • A leading 0 (zero) on an integer constant means octal. • A leading 0x or 0X means hexadecimal • Example • Decimal 31 • 037 in octal or 0x1f or 0X1F in hex • Octal and hexadecimal constants may also be followed by L to make them long and U to make them unsigned • 0XFUL: an unsigned long constant with value 15 decimal Types, Operators, and Expressions
2.3 Constants • A floating constant (single-precision) is written with a terminal f or F • 123.4F • A double constant • 123.4 • 1e-2 • A long double is written with a terminal l or L • 123.4L Types, Operators, and Expressions
2.3 Constants • A character constant is an integer • Written as one character with single quotes • ‘x’ • The value of a character constant is the numeric value of the character • ‘0’ has the value 48 • Certain character can be represented in character and string constants by escape sequences • \n : newline Types, Operators, and Expressions
2.3 Constants • An arbitrary byte-size bit pattern can be specified • by ‘\000’ where 000 is one to three octal digits (0…7) • by ‘\xhh’ where hh is one or more hexadecimal digits (0…9, a…f, A…F) • Example • #define VTAB ‘\013’ or ‘\xb’ • #define BELL ‘\007’ or ‘\x7’ • The null character • ‘\0’ represents the character constant with value zero Types, Operators, and Expressions
2.3 Constants • The complete set of escape sequence is Types, Operators, and Expressions
2.3 Constants • A constant expression • An expression involves only constants • Evaluated during compilation rather than run-time • Examples #define MAXLINE 1000 char line[MAXLINE+1]; • or #define LEAP 1 int days[31+28+LEAP+31+30+31+30+31+31+30+31+30+31]; Types, Operators, and Expressions
2.3 Constants • A string constant, or string literal • A sequence of zero or more characters surrounded by double quotes • “I am a string” or “” (empty string) • Internal representation • A null character ‘\0’ at the end • The quotes are not part of the string • Only to delimit it Types, Operators, and Expressions
Exercise 2-2 • Write a function my_strlen to determine the length of its character string argument s. • <string.h> Types, Operators, and Expressions
2.3 Constants • ‘X’ is not the same as “X” • ‘X’ • an integer used to produce the numeric value of the letter X in the machine’s character set • “X” • An array of characters that contains one character (the letter X) and a ‘\0’ Types, Operators, and Expressions
2.4 Declarations • The concept of “instance” • All variables must be declared before use • int lower, upper, step; • char c, line[1000]; • Be initialized in its declaration • char esc = ‘\\’; • int i = 0; • int limit = MAXLINE + 1; • float eps = 1.0e-5; Types, Operators, and Expressions
2.4 Declarations • The qualifier const can be applied to the declaration of any variable to specify its value • Its value will not be changed • Example: • const double PI = 3.1415926; • const char msg[] = “warning: “; Types, Operators, and Expressions
2.5 Arithmetic Operators • Binary arithmetic operators • + (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus or Remainder) • Integer division truncates any fractional part. • 7 / 4 = 1, 17 / 5 = 3 • Modulus cannot by applied to float or double • 7 % 4 = 3, 17 % 5 = 2 • The same precedence • *, /, % • +, - Types, Operators, and Expressions
Exercise 2-3 • A year is a leap year if it is divisible by 4 but not by 100, except that years divisible by 400 are leap years. Please write a program to test if a given year is a leap one or not? • scanf Types, Operators, and Expressions
2.6 Relational and Logical Operators • Relational operators • >, >=, <, <= • Equality operators • ==, != • Logical operators • &&, || • Expressions connected by && or || are evaluated left to right, and evaluation stops as soon as the truth or falsehood of the result is known. Types, Operators, and Expressions
2.6 Relational and Logical Operators • The numeric value of a relational or logical expression • 1 if the relation is true • 0 if the relation is false • Unary negation operator : ! • Convert a non-zero operand into 0 • Convert a zero operand into 1 • A common use • if (!valid) • If (valid==0) Types, Operators, and Expressions
2.7 Type Conversions • When an operator has operands of different types, they are converted to a common type • Convert a “narrower” operand into a “wider” one without losing information • Convert an integer to floating point in an expression like f + I • Expressions that might lose information • May draw a warning, but not illegal • Assign a floating-point type into an integer Types, Operators, and Expressions
2.7 Type Conversions • A char is just a small integer • Chars may be freely used in arithmetic expression • atoi: convert a string of digits into its numeric equivalent int atoi(char s[]) { int i, n; n = 0; for ( i = 0; s[i] >= ‘0’ && s[i] <= ‘9’; ++i ) n = 10 * n + ( s[i] - ’0’ ); return n; } Types, Operators, and Expressions
2.7 Type Conversions • An example of char to int conversion lower: convert c to lower cases; ASCII only int lower(int c) { if ( c >= ‘A’ && c <= ‘Z’ ) return c + ’a’ - ’A’; else return c; } Types, Operators, and Expressions
Exercise 2-4 • Write the function htoi(s), which converts a string of hexadecimal digits (including an optional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through 9, a through f, and A through F. Types, Operators, and Expressions
2.8 Increment and Decrement Operators • Increment operator + + adds 1 to its operand • Decrement operator - - subtracts 1 • Can be placed before or after the variable • n++ • Increment n after its value has been used • ++n • Increment n before its value has been used • An expression like (i+j)++ is illegal. Types, Operators, and Expressions
2.8 Increment and Decrement Operators Example: • If n is 5, then • x = n++; set x to 5 • x = ++n; set x to 6 • In both cases, n becomes 6. Types, Operators, and Expressions
2.8 Increment and Decrement Operators • The function squeeze(s, c) • Remove all occurences of the character c from the string s /* squeeze: delete all c from s */ void squeeze(char s[], int c) { int i,j; for (i=j=0; s[i]!=‘\0’; i++) If (s[i] != c) s[j++] = s[i]; s[j] = ‘\0’; } Types, Operators, and Expressions
Exercise 2-5 • Write an alternate version of squeeze(s1, s2) that deletes each character in s1 that matches any character in the string s2. Types, Operators, and Expressions
Exercise 2-6 • Write the function any(s1, s2), which returns the first location in the string s1 where any character from the string s2 occurs, or -1 if s1 contains no characters from s2. • The standard library function strpbrk does the same job but returns a pointer to the location. Types, Operators, and Expressions
2.9 Bitwise Operators • Six operators for bit manipulation • & • | • ^ • << • >> • ~ • Only be applied to integral operands • char, short, int, long, whether signed or unsigned bitwise AND bitwise inclusive OR bitwise exclusive OR left shift right shift one’s complement (unary) Types, Operators, and Expressions
2.9 Bitwise Operators • AND operator & • To mask off some set of bits • n = n & 0177 • Set to zero all but the low-order 7 bits of n • OR operator | • To turn bits on • x = x | SET_ON • Set to one in x the bits that are set to one in SET_ON Types, Operators, and Expressions
2.10 Assignment Operators and Expressions • Assignment operator • Expression i = i + 2 can be written in the compressed form i += 2 • Most binary operators have a corresponding assignment op = , where op is one of the following: • +, -, *, /, %, <<, >>, &, ^, | • expr1 op = expr2is equivalent to expr1 = (expr1) op (expr2) Types, Operators, and Expressions
2.10 Assignment Operators and Expressions • x *= y+1 • x = x * (y+1), rather than x = x * y + 1 • Write a function bitcount counts the number of 1-bits in its integer argument. • int bitcount ( unsigned x ) Types, Operators, and Expressions
Exercise 2-7 • In a two’s complement number system, x &= (x-1) deletes the rightmost 1-bit in x. Explain why. Use this observation to write a faster version of bitcount. Types, Operators, and Expressions
2.11 Conditional Expressions • Ternary operator “?:” • expr1 ? expr2 : expr3 • expr1 is evaluated first • If it is non-zero (true), expr2 is evaluated. • Otherwise, expr3 is evaluated. • if (a>b) z = a; else z = b; • z = (a>b) ? a : b; Types, Operators, and Expressions
2.11 Conditional Expressions • An example • printf(“You have %d item%s.\n”, n, n==1 ? ”” : ”s”); Types, Operators, and Expressions
2.12 Precedence andOrder of Evaluation Types, Operators, and Expressions
2.12 Precedence andOrder of Evaluation Types, Operators, and Expressions
2.12 Precedence andOrder of Evaluation • C does not specify the order in which the operands of an operator are evaluated. • Wrong • printf(“%d %d\n”, ++n, power(2, n)); • Solution • ++n; • printf(“%d %d\n”, n, power(2, n)); Types, Operators, and Expressions