Sei sulla pagina 1di 50

Types, Operators, and Express

ions
Background
 Basic data objects in a program
 Variable, constant
 Data types of variables
 Operators on variable
 Expressions to assign values to
variables
Outline
 Variable name
 Data types and sizes
 Constants
 Declarations
 Arithmetic operators
 Relational and logical operators
 Type conversions
 Increment and decrement operators
 Bitwise operators
 Assignment operators and expressions
 Conditional expressions
 Precedence and order of evaluation
Variable names
 Naming conventions
 Consist of letters and digits and “_”
 Case sensitive
 First character must be a letter
 A habit
 Lower case for variable names
 Upper case for symbolic constants
 Avoid reserved keywords
 Meaningful names
Outline
 Variable name
 Data types and sizes
 Constants
 Declarations
 Arithmetic operators
 Relational and logical operators
 Type conversions
 Increment and decrement operators
 Bitwise operators
 Assignment operators and expressions
 Conditional expressions
 Precedence and order of evaluation
Data types and sizes
 char : one byte
 int : one integer, 16 or 32 bits
Machine
dependent
 short : short integer, 16 bits
 long : long integer, 32 bits
 float : single-precision floating point
 double: double-precision floating point
Data types and sizes (cont.)
 unsigned char : 8 bits, 0 to 255
 signed char : 8 bits, -128 to 127
 unsigned int
 signed int

 <limits.h> and <float.h>


Outline
 Variable name
 Data types and sizes
 Constants
 Declarations
 Arithmetic operators
 Relational and logical operators
 Type conversions
 Increment and decrement operators
 Bitwise operators
 Assignment operators and expressions
 Conditional expressions
 Precedence and order of evaluation
Constants
 Integer constants
 1234, 123456789L, 1234U
 Floating-point constants
 123.4, 1e-2, 123.4F
 Octal and hexadecimal constants
 037, 0x1F
 Character constants (value is integer)
 ‘x’, ‘0’ (value is 48)
Constants (cont.)
 Escape sequences for characters
 \n: newline, \t: tab, \r: carriage return,…
 Octal for byte-sizes pattern
 ‘\013’ – tab, value = 11
 Hexadecimal for byte-sizes pattern
 ‘\xb’ – tab, value = 11
Constant expressions
 Constant expressions are evaluated
during compilation rather run-time
 #define MAXLINE 1000
 char line[MAXLINE+1];

compile

char line[1000+1];
String constants
 Character arrays = strings
“Hello\n”
H e l l o \n \0

Null character

‘x’ : character
“x” : string contains x \0
String constants (cont.)
 Count the string length(up to ‘\0’)
int strlen(char s[])
{
int i;

i=0;
while (s[i] != ‘\0’)
++i;
return i;
}
Enumeration constants
enum months { JAN=1, FEB, MAR, APR, MAY, JUN, JUL
AUG, SEP, OCT, NOV, DEC};

#define JAN 1
#define FEB 2
=> #define MAR 3
Automatically generate …
corresponding constants #define DEC 12
Outline
 Variable name
 Data types and sizes
 Constants
 Declarations
 Arithmetic operators
 Relational and logical operators
 Type conversions
 Increment and decrement operators
 Bitwise operators
 Assignment operators and expressions
 Conditional expressions
 Precedence and order of evaluation
Declaration
int lower; /* …*/
int lower, upper, step; int upper;
char c, line[1000];  int step;
char c;
char line[1000];

Initialize in declarations
char esc = ‘\\’; For automatic variables,
int i = 0; this initialization is done
int limit = MAXLINE + 1; when the function is entered
float eps = 1.0e-5;
Declaration (cont.)
 Qualifier const
const double e = 2.71828182845905;
const char msg[] = “warning: “;

Values of these variables can not be changed


? Comparing with symbolic constant
Outline
 Variable name
 Data types and sizes
 Constants
 Declarations
 Arithmetic operators
 Relational and logical operators
 Type conversions
 Increment and decrement operators
 Bitwise operators
 Assignment operators and expressions
 Conditional expressions
 Precedence and order of evaluation
Arithmetic operators
 +,-,*,/
Applied to integer and float
 %: modulus 求餘數
if( (year%4 == 0 && year%100 != 0) || year%400 == 0)
 precedence
 Left to right
unary +, - > binary *,/,% > binary +, -
Outline
 Variable name
 Data types and sizes
 Constants
 Declarations
 Arithmetic operators
 Relational and logical operators
 Type conversions
 Increment and decrement operators
 Bitwise operators
 Assignment operators and expressions
 Conditional expressions
 Precedence and order of evaluation
Relational operators
 Relational operators
> >= < <=
V
== !=
 Arithmetic operators > relational operators
i < lim -1  i < (lim –1)
 Relational and logical expression produces
0 or 1 (i<lim) - 1
Logical operators
 && (AND) , || (OR)
 Evaluate from left to right, stop as soon as
the truth or false of the result is known
for (i=0; i<lim-1 && (c=getchar())!=‘\n’ && c != EOF; ++i)
s[i] = c;

 ! (NOT)
if( ! valid)  if (valid == 0)
Outline
 Variable name
 Data types and sizes
 Constants
 Declarations
 Arithmetic operators
 Relational and logical operators
 Type conversions
 Increment and decrement operators
 Bitwise operators
 Assignment operators and expressions
 Conditional expressions
 Precedence and order of evaluation
Type conversion
 When operator has operands of
different types
 Rule
 Convert a “narrow” operand into a “wider”
one without losing information
Type conversion : example 1
char to int
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;
}

*there is already an atoi() function in <stdlib.h>


Type conversion : example 2
char to int
int lower(int c)
{
if(c >= ‘A’ && c <= ‘Z’)
return c + ‘a’-’A’; works for ASCII code
else
return c;
}

•<ctype.h> contains a family of functions that provide


tests and conversions that are independent of char. set
ctype.h
 Functions for testing characters
isdigit(c) decimal digit
isxdigit(c) hexadecimal digit
islower(c) lower-case letter
isupper(c) upper-case letter
isalpha(c) isupper(c) or islower(c) is true
isalnum(c) isalpha(c) or isdigit(c) is true
isspace(c) space, formfeed, newline, cr, tab, vertical tab

int tolower(int c) convert c to lower case
int toupper(int c) convert c to upper case
Type conversion: assignment
 Left hand side = right hand side

Example 1 Example 2
int i; float x;
char c; int i;

i = c; x = i;
c = i; i = x;
Type conversion: argument in
function calls and cast
 Cast: forced type conversion
 (type-name) expression
 Example: int n;

Defined in sqrt((double) n);


<math.h>
Its value is converted
before passing to sqrt
Type conversion: argument in
function calls and cast (cont.)
 If arguments are declared by a function
prototype, then there will be automatic
type conversion
double sqrt(double);

root2 = sqrt(2); root2 = sqrt(2.0);

* Compiler issue
Outline
 Variable name
 Data types and sizes
 Constants
 Declarations
 Arithmetic operators
 Relational and logical operators
 Type conversions
 Increment and decrement operators
 Bitwise operators
 Assignment operators and expressions
 Conditional expressions
 Precedence and order of evaluation
Increment and decrement
operators
 Increment
 x=n++; postfix (increment after…)
 x=++n; prefix (increment before…)

If n=5, what happens to x?


x=5
x=6
 (i+j)++ is not legal
 Decrement
 x= n--;
 x=--n;
Increment and decrement
operators: example 1
/* delete c from s */
void squeeze(char s[], int c)
{
int i, j;

for(i=j=0; s[i]!=‘\0’; i++)


if (s[i] != c){
if(s[i] != c)
s[j] = s[i];
s[ j++]=s[i];
j++;
s[j] = ‘\0’;
}
}
i
j
Increment and decrement
operators: example 2
/* concatenate t to end of s */
i
void strcat ( char s[], char t[])
{
int i, j; s ggyy\0

i = j = 0; t ggyyggy\0
while ( s[i] != ‘\0’)
i++;
j
while( (s[i++] = t[j++]) != ‘\0’)
;
}
Outline
 Variable name
 Data types and sizes
 Constants
 Declarations
 Arithmetic operators
 Relational and logical operators
 Type conversions
 Increment and decrement operators
 Bitwise operators
 Assignment operators and expressions
 Conditional expressions
 Precedence and order of evaluation
Bitwise operators
 6 bitwise operators
& bitwise AND
| bitwise inclusive OR
10100110
^ bitwise exclusive OR …
<< left shift 00100101
>> right shift
~ one’s complement
 Apply to integral operands
 char, short, int, long
Bitwise operators (cont.)
 AND: used to mask some bits
n = n & 0177
01 111 111

 OR: used to turn bits on(1)


x = x | SET_ON;

Be cautious!!! Logic operators && , ||


If x=1, y=2 x&y=0
x && y = 1
Bitwise operators (cont.)
 Shift operators
 x << 2 00011011 -> 01101100
 x >> 2 00011011 -> ?0000110
sign?
Dependent on machine

 NOT: ~
 x = x & ~077
Bitwise operators: example
/* getbits: get n bits from position p */
unsigned getbits (unsigned x, int p, int n)
{
return (x >> (p+1-n) & ~(~0 << n));
}

Ex. getbits(x, 4, 3)
76543210

76543210 00000111
11111000
11111111
Outline
 Variable name
 Data types and sizes
 Constants
 Declarations
 Arithmetic operators
 Relational and logical operators
 Type conversions
 Increment and decrement operators
 Bitwise operators
 Assignment operators and expressions
 Conditional expressions
 Precedence and order of evaluation
Assignment operators
 Example:
i = i+2;  i += 2;
 General form
 expr1 = (expr1) op (expr2)
 expr1 op= expr2
 op can be any binary operators
 Example:
x *= y+1  x = x * (y+1);
Assignment operators:
example
/* bitcount: count number of 1-bits in x */
int bitcount ( unsigned x )
{
int b;

for( b=0; x != 0; x >>= 1)


if( x & 01 )
b++;
return b;
}
Assignment operators (cont.)
 Advantages:
 Correspond better to the way people think
 “add 2 to i”, “increment i by 2”
 “take i, add 2, then put the result back in i”
 Simplify complex expression
 yyval[yypv[p3+p4]+yypv[p1+p2]] += 2;
 May help compiler to produce efficient cod
e
Assignment expression
 Assignment statement has a value, can
occur in expressions
while ( (c=getchar()) != EOF)

left hand side = right hand side


Data type = the data type of left operand
Value = the value after assignment
Outline
 Variable name
 Data types and sizes
 Constants
 Declarations
 Arithmetic operators
 Relational and logical operators
 Type conversions
 Increment and decrement operators
 Bitwise operators
 Assignment operators and expressions
 Conditional expressions
 Precedence and order of evaluation
Conditional expressions
if ( a > b)
z = a;
Else  z = (a > b) ? a : b;
z = b; Conditional expression

General form:
expr1 ? expr2 : expr3;
Conditional expression (cont.)
 Advantage: it generates compact code
Example: print 10 array elements per line
for ( i=0; i < n; i++)
printf(“%6d%c”, a[i], (i%10 == 9 || i == n-1)? ‘\n’ : ‘ ’);

Example: 複數形
Printf(“You have %d item%s.\n”, n, n == 1 ? “” : “s”);
Outline
 Variable name
 Data types and sizes
 Constants
 Declarations
 Arithmetic operators
 Relational and logical operators
 Type conversions
 Increment and decrement operators
 Bitwise operators
 Assignment operators and expressions
 Conditional expressions
 Precedence and order of evaluation
Precedence of operators
() [] -> .
! ~ ++ -- + - * & (type) sizeof
* / %
+ -
If you are not sure
<< >> of anything,
< <= > >= Use brackets!!!
== !=
&
^
|
&&
||
?:
= += -= *= /= %= &= ^= |= <<= >>=
,
Order of evaluation
 NO specified order of evaluation except
&&, ||, ?:
x = f() + g(); Not sure f or g is evaluated first

printf(“%d %d\n”, ++n, power(2, n));

DO NOT write code that depends on order of evaluation

++n;
printf(“%d %d\n”, n, power(2, n));

Potrebbero piacerti anche