chap. 2. types, operators, and expressions

17
1 Chap. 2. Types, Operators, and Expressions 2.1 Variable Names 2.2 Data Types and Sizes 2.3 Constants 2.4 Declarations Imperative Programming, B. Hirsbrunner, diuf.unifr.ch/pai/ip Session 3, 4 March 2008 2.5 Arithmetic Operators 2.6 Relational and Logical Operators 2.7 Type Conversations 2.8 Increment and Decrement Operators 2.9 Bitwise Operators 2.10 Assignment Operators and Expressions 2.11 Conditional Expressions 2.12 Precedence and Order of Evaluation

Upload: hea

Post on 04-Jan-2016

31 views

Category:

Documents


0 download

DESCRIPTION

Chap. 2. Types, Operators, and Expressions. 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations. 2.5Arithmetic Operators 2.6Relational and Logical Operators 2.7Type Conversations 2.8Increment and Decrement Operators 2.9Bitwise Operators. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chap. 2. Types, Operators, and Expressions

1

Chap. 2. Types, Operators, and Expressions

2.1 Variable Names

2.2 Data Types and Sizes

2.3 Constants

2.4 Declarations

Imperative Programming, B. Hirsbrunner, diuf.unifr.ch/pai/ip Session 3, 4 March 2008

2.5 Arithmetic Operators

2.6 Relational and Logical Operators

2.7 Type Conversations

2.8 Increment and Decrement Operators

2.9 Bitwise Operators

2.10 Assignment Operators and Expressions

2.11 Conditional Expressions

2.12 Precedence and Order of Evaluation

Page 2: Chap. 2. Types, Operators, and Expressions

2

2.1 Variable Names

Names are made of letters and digits, but :

– the first character must be a letter

– the underscore “_” counts as a letter (useful for improving readability)

– don’t begin variable names with underscore (since library routines often use such names)

Case sensitivity

– Upper and lower case are distinct, so x and X are two different names

– Traditional C pratice is to use :• lower case for variable names

• upper case for symbolic constants

Miscellaneous

– At least the first 31 characters of an internal name are significant (!!!)

– For external names, the standard guarantees uniqueness only for 6 characters (!!!)

– Keywords like int, float, if, else, etc., are reserved: you can’t use them as variable names

Page 3: Chap. 2. Types, Operators, and Expressions

3

2.2 Data Types and Sizes

Basic data types– char, int, float, double

Qualifiers– short int, long int

• short is often 16 bits, long 32 bits, and int either 16 or 32 bits

– signed, unsigned : apply to char and any integer• if chars are 8 bits, unsigned chars have values between 0 and 255,

while signed chars between -128 and 127 (in a two’s complement machine)

– long double

Standard Header Files (see [KR88], p.257)– <limits.h> defines constants for the sizes of integral types

• Examples: INT_MIN, INT_MAX, LONG_MAX, LONG_MIN

– <float.h> defines constants related to floating-point arithmetic

Page 4: Chap. 2. Types, Operators, and Expressions

4

Signed integer (1/3)

Signed magnitude• The leftmost bit is the sign bit

0 1 2 3

000 100001 101 110 111010 011

-0 -1 -2 -3

One’s complement• To negate a number, replace each 1 by 0 and each 0 by 1

0 1 2 3

000 100001 101 110 111010 011

-3 -2 -1 -0

Page 5: Chap. 2. Types, Operators, and Expressions

5

Signed integer (2/3)

0

1

2

3

Two’s complement• First step: as one’s complement• Second step: add one to the result

000

100

001

101

110

111

010

011-4

-1

-2

-3

Page 6: Chap. 2. Types, Operators, and Expressions

6

Signed integer (3/3)

-4

-3

-2

-1

Excess 2m-1 (here m=3)• a number is stored as its true value plus 2m-1

000

100

001

101

110

111

010

0110

3

2

1

Page 7: Chap. 2. Types, Operators, and Expressions

7

2.3 Constants

1234 : integer constant

123456789L : long constant

1234U : unsigned constant

123456789UL : unsigned long

Complete set of escape sequences:

\a \b \f \n \r \t \v

\\ \? \’ \” \ooo \xhh

‘\ooo’ : ooo is one to three octal digits (0 .. 7)

‘\xhh’ : hh is 1 or 2 hexadecimal digits (0 .. 9, a .. f, A .. F)

‘x’ : character constant (The value of ‘x’ is the numeric value of x in the machine’s character set)

01234 : octal (with a leading zero)

0X1234 : hexadecimal

Enumeration constant :

enum boolean { NO, YES }

enum escape { BELL = ‘\a’, TAB = ‘\t }

“I am a string” : string constant

“hello ” “world” : string concatenation(a string constant is a array of characters,

with a null character ‘\0’ at the end;

‘\0’ represents the character with value zero)

Be careful : ‘x’ is a character constant and

“x” is string constant

Page 8: Chap. 2. Types, Operators, and Expressions

8

2.4 Declarations

• All variables must be declared before use

• A declaration specifies a type, and contains a list of one or more variables of that type, as in :

int lower, upper, step;char c, line[1000];

• A variable may be initialized in its declaration, as in :char esc = ‘\\’;int i = 0, limit = MAXLINE + 1;float eps = 1.0e-5;

• External and static variables are intialized to zero by default

• Automatic variables for which there is no explicit initializer have undefined (garbage) values.

• const qualifier can be applied to the declaration of any variable to specify that its value will not be changed

const double e = 2.71828182845905;const char msg[] = “warning: “;int strlen(const char[]);

Page 9: Chap. 2. Types, Operators, and Expressions

9

2.5 Arithmetic Operators

• +, -, *, /, %

– The integer division / truncates any fractional part

– The expression x % y, which reads “x modulus y”, produces the remainder when x is divided by y

• Machine dependance for negative operands

– The direction of truncation for /

– The sign of the result for %

– The action taken on overflow or underflow

• Precedence rules

– The binary + and - operators have the same precedence, which is lower than the precedence of *, /, and %, which is in turn lower than the unary + and -.

– Arithmetic operators associate left to right.

Page 10: Chap. 2. Types, Operators, and Expressions

10

2.6 Relational and Logical Operators

• Relational operators: >, >=, <, <=

• Equality operators: ==, !=

• Logical operators: &&, ||

– Expressions connected by && and || are evaluated left to right, and evaluation stops as soon as the truth or falsehood of the result is known

– Example:

for (i=0; i<lim-1 && (c=getchar()) != ‘\n’ && c != EOF; ++i)

s[i] = c;

– By definition, the numeric value of a relational or logical expression is 1 if the relation is true, and 0 if the relational is false

• Unary negation operator !

– Converts a non-zero operand into 0, and a zero operand into 1

– Example: if (!valid) is equivalent to if (valid == 0)

Page 11: Chap. 2. Types, Operators, and Expressions

11

2.7 Type Conversation

• Explicit type conversions : cast unary operator

– (type-name) expression

– Example: (double) n

• Arithmetic Conversion Rules

Vertical conversions are always performedHorizontal conversions are performed only when necessary

int –> unsigned –> long –> double

char, short int float

Page 12: Chap. 2. Types, Operators, and Expressions

12

2.8 Increment and Decrement Operators

• The increment operator ++ adds 1 to its operand, while the decrement operator -- substracts 1

• ++ and -- may be used either as prefix or postfix operators:

– ++n increments n before its value is used

– n++ increments n after its value has been used

• Example if n is 5, then

x = ++n;sets x to 6, but

x = n++; sets x to 5. In both cases, n becomes 6.

Page 13: Chap. 2. Types, Operators, and Expressions

13

2.9 Bitwise Operators

& bitwise AND

| bitwise inclusive OR

^ bitwise exclusive OR

<< left shift

>> right shift

~ one’s complement (converts each 1-bit into a 0-bit and vice versa)

Examples• n = n & 0177 (sets to zero all but the low-order 7 bits of n)

• n = n & ~077 (sets the last 6 bits of n to zero)

Illustration/* getbits: get n bits from position p */unsigned my_getbits(unsigned x, int p, int n){ return (x >> (p+1-n)) & ~(~0 << n);}

p 0p - n

n p - n + 1

moves the desired n bits to the rightplaces 0-bits in the rightmost n bits and 1-bits elsewhere

Page 14: Chap. 2. Types, Operators, and Expressions

14

2.10 Assignment Operators and Expressions

• Most binary operators have a corresponding assignment operator op=, where op is one of :

+ – * / % << >> & ^ |

• If expr1 and expr2 are expressions, thenexpr1 op= expr2

is equivalent to expr1 = expr1 op (expr2)

except that expr1 is computed only once

• Assignment expression has the same value as the left expression of the assignment

Example: while ((c = getchar()) != EOF) {…}

Page 15: Chap. 2. Types, Operators, and Expressions

15

2.11 Conditional Expressions

• The conditional expression

expr1 ? expr2 : expr3

provides an alternate way to write the if-else statement.

• Note that the operator “?:” has three operands. Such an operator is commonly called a ternary operator.

• Example

z = (a > b) ? a : b; /* z = max(a,b) */

Page 16: Chap. 2. Types, Operators, and Expressions

16

2.12 Precedence and Order of Evaluation

• The rules for precedence and associativity of all operators are summarized in Table 2.1.

• C, like most languages, does not specify the order in which the operands of an operator are evaluated. The exceptions are (with a guaranted left to right evaluation) :

&& ||

?:

,

• Examples

– In a statement like "x = f() + g();" f may be evaluated before g or vice versa.

– Logical expressions are evaluated from left to right and the evaluation is stopped as soon as the result TRUE or FALSE is established.

Page 17: Chap. 2. Types, Operators, and Expressions

17

Table 2.1: Precedence and Associativity of Operators

Associativity Operators

left to right () [] -> .

right to left ! ~ ++ -- + - * (type) sizeof

left to right / %

left to right + -

left to right << >>

left to right < <= > >=

left to right == !=

left to right &

left to right ^

left to right |

left to right &&

left to right ||

left to right ?:

right to left = += -= *= /= %= &= ^= |= <<= >>=

left to right ,

Remark. Unary & +, -, and * have higher precedence than the binary forms.