0% found this document useful (0 votes)
3 views

Chapter 02

Uploaded by

MD HEZBULLAH
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 02

Uploaded by

MD HEZBULLAH
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 95

The C Programming Language

Chapter 2 Types, Operators & Expressions

Chapter 2
Types, Operators & Expressions

类型、运算符 & 表达式


Outline

1. Data, Data Types & Size


2. Constants and Variables
3. Operators & Expression
4. Type Conversion
Problem
There is a circle swimming pool, we want
to decorate it. So circumference needed.

Mathematical C 2r
formula:

How to calculate C with program?


Problem
How to implement mathematical
formula?
expression
expression
How to input and store
data? operand +operator
operand +operator

constant
constant
variable
variable

operator
operator
How to process data?
The C Programming Language
Chapter 2 Types, Operators & Expressions

 Variables and constants:


basic data objects
 Declarations:
variables
types
initial values
 Operators:
what is to be done
 Expressions:
Combine variables and constants to
produce new values
Data, Data Types and Sizes

Progra data storage


m data process
Arithmetic:+ , - , * , \
Assignment:=
Operators Relational (comparison):<,>
Logical: and, or, orelse, not
Expression Bitwise Operators: and, or
Constants
Operands Variables
Function call
Data, Data Types and Sizes

 Data - > the processed object of a program.


sum = 1+2; printf(“%d”,sum);
sum = n1 + n2;

 Data type - > define data structure, data size, data


operation
char c = ‘a’; chat *p = “abc”;
int i = 2;
int d = 3/i;
 Data Types in C

int (整型) : 1, 32, 100


char (字符型) : 0,2,a
Basic types
float (浮点型)
(基本类型)
double

Pointer type
Data type (指针类型)
数据类型 array (数组)
Construction types struct (结构)
(构造类型) union (联合)
enum (枚举)
void (空类型)
Data Types in C
Guess what type it is

int 6 101 -11

Floating 6.1 101.1 -11.1


point

char 6 a b
How does memory store data

Would
Would you
you like
like aa single
single
Data are various. Two room,
room, aa double
double room,
room, aa
Two people,
people, live
live in
in
four-room
four-room or
or aa
First, apply a aa double
double room.
room.
presidential
presidential suite?
suite?
suitable space to
the data according
to the demand of
data (i.e. type),
and memory is
like a hotel.
Types and rooms

Types Memory space Hotel room


Corresponding
char 1byte single room

Corresponding
short 2byte double room

Corresponding
int 2/4byte Double/four-room

Corresponding
double 8byte presidential suite
The letters in perfume

char
int How many
parts does a
car have?
Keywords bytes Value range
int 16 -32768~32767
short 16 -32768~32767
long 32 -2147483648~2147483647
float 32 3.4e-38~3.4e38
double 64 1.7e-308~1.7e308
Number
Sho
rt
of apples
in the
basket
long

Number of celestial
bodies in the universe
How many
milliliters of

float
orange juice are
there?
The distance
between two cities
doubl
e
Fruit in the
tray
enu
m
 Data Sizes

 Different data type has different storage Size

 Same data type on different Platform has different


storage Size

 Just use sizeof(data type) to get it.

sizeof (int); sizeof(char); sizeof(float);


sizeof(double);
Constants and Variables
 Constants

 its value can not be changed during


program execution.
Constants and Variables
 Constants Decimal 100 , 125 , -100 , 0
Integer constant Octal 0123, -011
Hexadecimal0x123
Decimal point
Floating-point
Octal or constant 3.14 , 0.125 , -3.789
Hexadec Exponent
(实型常量)
imal 1e3 1.8e-3
here? Character constant (字符)
‘A’ ‘g’ ‘0’ ‘2’ ‘+’ ‘#’

String constant (字符串)


“abc” , “ I love C”
Symbolic constant (符号常量)
Chapter 2 Types, Operators & Expressions
2.1 Variable Names

2.1 Variable Names


letters (include “_”) and digits, begin with letter
upper case and lower case letters are DISTINCT
keywords like if, else, int, float, etc., are reserved
 Use lower case for variable names
and all upper case for symbolic constants.
Chapter 2 Types, Operators & Expressions
2.1 Variable Names

2.1 Variable Names

Example:
Legal variable names (or identifier):
sum, average, class, day, month,
student_name, _above,
lotus_1_2_3, basic,
The_C_Programming_Language
Illegal variable names:
M.D.Join, $123, #33, 3D64, a>b

Use short names for local variables,


longer names for external variables.
Chapter 2 Types, Operators & Expressions
2.2 Data Types & Sizes

2.2 Data Types & Sizes


 Basic data types in C:
char a single byte, holding ONE character (1 byte)
int an integer (2 or 4 bytes)
float single-precision floating point (4 bytes)
double double-precision floating point (8 bytes)

 Each basic type is “numerical value ” type. 


Chapter 2 Types, Operators & Expressions
2.2 Data Types & Sizes

 Some qualifiers can be applied to basic types:


 short , long + int :
short int sh / short sh (int can be omitted)
long int counter / long counter
 short 16 bits, long 32 bits, int either 16 or 32 bits
Chapter 2 Types, Operators & Expressions
2.2 Data Types & Sizes

 signed , unsigned + char or ANY integer


(signed can ALWAYS be omitted)
signed char (or char) values between -128~127
unsigned char values between 0~255
signed int (or int) values between -2n-1~2n-1-1
unsigned int values between 0~2n-1
Chapter 2 Types, Operators & Expressions
2.2 Data Types & Sizes

 function sizeof( ) return the size of the


type or variable.
char ch;
sizeof(char) 1
or
sizeof(ch)  1(byte)
sizeof(int) 2
sizeof(long int) 4
Chapter 2 Types, Operators & Expressions
2.3 Constants

2.3 Constants
Type Example remark
int 123, -456 int constants
long 123456789l or 123456789L
unsigned int 123u or 123U
unsigned long 123456789ul or 123456789UL
octal 037
hexadecimal 0x1f or 0X1F
float or double 123.4 or 1e-2; 123.4l or 123.4L float, double
float ONLY 123.4f or 123.4F constants

char ‘x’, ‘0’, ‘\n’, ‘\013’, ‘\xb’, ‘\x7’, ‘ ’ char constants

 the value of a character constant is the numeric value


of the character in the machine’s character set. For
example, ‘0’ has the value 48 (ASCII). 
Chapter 2 Types, Operators & Expressions
2.3 Constants

The complete set of escape sequences:


\a alert(bell) \\ backslash
\b backspace \? question mark
\f formfeed \’ single quote
\n newline \” double quote
\r carriage return \ooo octal number
\t horizontal tab \xhh hex number
\v vertical tab ‘\0’ null character, with value 0 (zero).
Chapter 2 Types, Operators & Expressions
2.3 Constants

An arbitrary bit pattern can be specified by


‘\000’ 000 is one to three octal digits(0…7)
’\xhh’ hh is one or more hexadecimal
digits(0…9,a…f,A…F)

Examples: symbolic constant !


#define VTAB ‘\013’ /* ASCII vertical tab*/
#define BEEP ‘\007’ /* ASCII beep character*/

#define VTAB ‘\xb’ /* ASCII vertical tab*/


#define BEEP ‘\x7’ /* ASCII beep character*/
character constants
string constant

‘M’ “hello ”
‘F’
‘a’ “sunshine
‘9’ ”
‘?’ ‘A’ “One”
“A”

Single character
“A ‘ ‘\0’
” A
Chapter 2 Types, Operators & Expressions
2.3 Constants

string constants:  Technically, a string constant is


an array of characters.
“I am a string”
I a m a s t r i n g \0

“”(null string)
\0

 function strlen(s): return the length of its character


string arguments, excluding the terminal ‘\0’.
strlen(“I am a string”) 13
strlen(“”)  0
Chapter 2 Types, Operators & Expressions
2.3 Constants

 strlen and other string


functions are declared in the
standard header <string.h> 
/* strlen: return length of s */ s[0] I
int strlen(char s[ ])
s[1]
{
int i; s[2] a

i = 0; s[3] m
while (s[i] != ‘\0’)
…… ……
i++;
return(i); s[N-
\0
1]
}
Chapter 2 Types, Operators & Expressions
2.3 Constants

 what is the difference between


‘x’ and “x”?

 ‘x’ is a integer, used to produce the numeric


value of the letter x in the machine’s
character set (always ASCII-120).

 “x” is an array of characters that contains


one character (the letter x) and a ‘\0’.
Chapter 2 Types, Operators & Expressions
2.3 Constants

Constant expression:
Is an expression that involves only constants. Such
expressions may be evaluated during compilation rather
than run-time.
Example:
#define MAXLINE 1000
char line[MAXLINE+1];
Chapter 2 Types, Operators & Expressions
2.3 Constants

enumeration constant ( 枚举常量 ):


An enumeration
 Namesis in
a list of constant
different integer
enumerations must be
values. distinct. Values need not be distinct in the
Examples: same enumeration. 
enum boolean {NO, YES}; /*NO = 0, and YES = 1*/

enum months {JAN = 1, FEB, MAR, APR, MAY, JUN,


JUL, AUG,SEP, OCT, NOV, DEC};
/*FEB is 2, MAR is 3, etc.*/

 As int, float, char, etc., boolean, escapes,


months declared here are different data type
respectively. 
Why do we need variables?

Memory address is not easy to remember, what to do?


Memory is like a hotel, where the location of data
storage is found by the alias of the room in memory .
room variable
Corresponding

Roomname
Room name Variablename
Variable name

One Roomtype
type Variabletype
type A variable
Room Variable
room
Guestsstaying
Guests staying Variablevalue
Variable value
Statement of variables

grammar data type Variable name = Variable value

The value of a variable can be changed

int a = 1; a = 3;
Example

long b = 2L; Change the


value of a
b=
variable
char c = ‘X’; 30000L;
c = ‘ 文’ ;
Character type
variable
Char keywords are used to define characters, and
characters can only be single characters enclosed
in single quotes
grammar char ch1
char ‘m’;;
ch1 == ‘m’

char ch2
char ‘a’;;
ch2 == ‘a’

char ch3
char ‘g’;;
ch3 == ‘g’

ch4 == ‘i’‘i’;;
char ch4
char

ch5 == ‘c’‘c’;;
char ch5
char
Check if the following characters are legitimate

‘M’ ‘&’

‘bool’ ‘5.2’
× ×
Character variable values are stored in memory as ASCII Dec Hex char
codes of characters, i.e. an unsigned integer, so character
data is allowed to perform arithmetic operations. 65 41 A

66 42 B
char ch1
char ‘b’-’a’;;
ch1 == ‘b’-’a’
1 … … …

90 5A Z

char ch2
char ‘c’+1;;
ch2 == ‘c’+1 ‘d’ … … …

97 6A a

98 6B b
char ch3
char ‘a’-32;;
ch3 == ‘a’-32
‘A’
… … …

122 7A z
Chapter 2 Types, Operators & Expressions
2.4 Declarations

2.4 Declarations
 All variables MUST be declared before use.
Declaration form:
type var1, var2, …, varN;
int lower, upper, step;
char c, line[1000];
 When a variable is not automatic (external and
static), the initializer must be a constant
 A variable
expression.mayThe initialization
also is done
be initialized inonce
its only
before the program starts executing. 
declaration.
general form:
char esc = ‘\\’;
int i = 0, j, k=1, m;
int limit = MAXLINE+1;
float eps = 1.0e-5;
Chapter 2 Types, Operators & Expressions
2.4 Declarations

const form:
specify that the value will not be changed.
Example:
const double pi = 3.1415926535;
const char message[] = “warning:”;

int strlen(const char []);


/* the function does not change that arry*/
Chapter 2 Types, Operators & Expressions
2.5 Arithmetic Operators

2.5 Arithmetic Operators


Binary arithmetic operators:
+, -, *, /, %
+, -, *, and / can be applied to any basic type,
but % can’t be applied to float and double.

ATTENTION!!!
type conversion occurs when different operands
Examples:
10.0/4  2.5, 10/4  2, -10/4  -2
10%3  1, -10%3  -1, 10 % 2  0
Chapter 2 Types, Operators & Expressions
2.5 Arithmetic Operators

/* leap year */
#include<stdio.h>
void main()
{
int year;
int i;
for(i=0;i<4;i++)
{
scanf("%d",&year);
if((year%4==0 && year%100!=0) || year%400==0)
printf("%d is a leap year\n", year);
else
printf("%d is not a leap year\n", year);
}
}
Chapter 2 Types, Operators & Expressions
2.6 Relational and Logical Operators

2.6 Relational and Logical Operators


Relational operators:
> >= < <= == !=
Precedence:
Arithmetic Ops. Relational Ops. Assignment Ops.

>
>=
what are the<calculating order
<=
of
the following expressions?
==
c>a+b; != c > (a + b)
a>b!=c; (a > b) != c
a=b>c; a = (b > c)
Chapter 2 Types, Operators & Expressions
2.6 Relational and Logical Operators

Relational expression
Examples:
a>b  The value of R. Exp is
a+b > b+c a logical value: TRUE /
(a=3) > (b=5)
FALSE
‘a’ < ‘b’ ( In C, 1 -- TRUE , 0 – FALSE ) 
(a>b) > (b<c)

 Let a = 3, b = 2, c = 1, then what are the


results of the following R. Exps?
a>b 1
(a > b) == c 1
b+c<a 0
d=a>b d=1
f=a>b>c f=0
Chapter 2 Types, Operators & Expressions
2.6 Relational and Logical Operators

Logical operators
&& || !
a && b if a, b are both TRUE, then a && b
is TRUE;
a || b if one of a and b is TRUE, then
a || b is TRUE;
!a if a is TRUE, then !a is FALSE.

precedence:
“!” > “&&” > “||”
associativity:
!: unary operator
&&, || : from left to right
Chapter 2 Types, Operators & Expressions
2.6 Relational and Logical Operators

precedence:
Operator

!
arithmetic operators higher
relational operators
&&
||
lower
=

As logical result, TRUE →1 and FALSE → 0


As logical judgement, nonzero → TRUE, 0 → FALSE
Chapter 2 Types, Operators & Expressions
2.6 Relational and Logical Operators

Example:
(1) if a = 4, then !a  0
(2) if a=4,b=5, then a&&b  1,a||b => 1,!a&&b  0
(3) 4&&0||2  1
(4) ‘c’ && ‘d’  1 (because ‘c’ and ‘d’ are both nonzero)
(5) 5 > 3 && 2 || 8 < 4 - !0
 1 && 2 || 8 < 4 - !0
 1 || 8 < 4 - !0
 1 || 8 < 4 - 1
 1 || 8 < 3
 1 || 0
1
Chapter 2 Types, Operators & Expressions
2.6 Relational and Logical Operators

When evaluating a logical expression, not all logical


operators are evaluated. Only when next logical
operator must be evaluated, so that the expression
including the operator has a result.
Example 1:
Let a = 1, b = 2, c = 3, d = 4, m = 1, and n = 1, then
(m = a>b) && (n = c>d)
=> 0 && (n = c>d) => 0
m = 0, n=1
m || (n = c>d)
=> 1 || (n = c>d) => 1
n=1

Example 2: leap year


(year%4==0 && year%100!=0) || year%400==0
Chapter 2 Types, Operators & Expressions
2.7 Type Conversion

2.7 Type Conversion


 When an operator has operands of different
types, they are converted to a common type
according to a small number of rules. e.g.:
10 + ‘a’ + 1.5 - 8765.1234*’b’
Chapter 2 Types, Operators & Expressions
2.7 Type Conversion

General conversion rules:


“narrower” => “wider”

double ( float )
higher
unsigned long

long

unsigned
lower
int char, short
Chapter 2 Types, Operators & Expressions
2.7 Type Conversion

Example 1:
Suppose: int i; float f; double d; long e;
10 + ‘a’ + i * f - d /e
(1) 10+ ‘a’,
‘a’ is converted to int 97, the result is int 107
(2) i*f,
i=>double, f=>double
(3) int 107 + the result of i*f ,
107=>double
(4) d/e,
e=>double, d/e=>double
(5) the result’s type of the expression is double.
Chapter 2 Types, Operators & Expressions
2.7 Type Conversion

Alphabet  Integer atoi


Example 2:
/* atoi: convert string s to integer */
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;
}

 c>=‘0’ && c<=’9’  isdigit(c) in


#include<ctype.h> 
Chapter 2 Types, Operators & Expressions
2.7 Type Conversion
#include<stdio.h>
#include<stdio.h> #include<ctype.h>
#include<ctype.h> int atoi(char s[ ]);
#include<transact.h> void main()
void main() {
{ printf("%d\n", atoi("12345"));
#include<stdio.h> }
printf("%d\n", atoi("12345"));
int atoi(char s[ ]);
}
void main() int atoi(char s[ ])
{ {
printf("%d\n", atoi("12345")); int i, n;
} n = 0;
for (i = 0; isdigit(s[i]); i++)
int atoi(char s[ ]) n = 10 * n + (s[i] - '0');
{ return n;
int i, n; }
n = 0;
for (i = 0; s[i] >= '0' && s[i] <= '9'; i++)
n = 10 * n + (s[i] - '0');
return n;
}
Chapter 2 Types, Operators & Expressions
2.7 Type Conversion

Example 3:
/* lower: convert c to lower case; ASCII only */
int lower(int c)
{
if (c >= ‘A’ && c <= ‘Z’)
return c + ‘a’ - ‘A’;
else
return c;
}

 In ASCII, ‘0’~’9’, ‘A’~’Z’ and ‘a’~’z’


are contiguous each. 
Chapter 2 Types, Operators & Expressions
2.7 Type Conversion
#include<stdio.h>
#include<stdio.h>
void main()
Argument passing (function {call):
void main()
{
In the absence of function prototype,
printf("%f\n", float(5/3
char and short
printf("%d\n", => int
5/3); }
} float => double
#include<stdio.
Explicit type conversion
(forced): void main()
#include<stdio.h> {
Example: printf("%f\n"
(double)a a’ value is converted the double
void main() } type;
(int)(x+y)
{ convert the value of x+y to int type;
(float)(5%3) convert the
printf("%d\n", value of 5%3 to float type.
float(5/3));
}
Chapter 2 Types, Operators & Expressions
2.7 Type Conversion

 When explicit type converting, a


medial variable is generated , and
main() { original variable’s type is not converted
float x; actually. 
int i;

x = 3.6;
i = (int)x;
printf(“x = %f, i = %d\n”, x, i);
}

x = 3.600000, i = 3
 what is the output of the program?
Chapter 2 Types, Operators & Expressions
2.8 Increment and Decrement Operators

2.8 Increment and Decrement


Operators
 Increment operator ++ adds 1 to its operand
 Decrement operator - - subtracts 1
++i, --i prefix operators , increments and
decrements i before its value is used.
i++, i-- postfix operators, increments and
decrements i after its value has been
used.
Examples: 
n=5; int i = 3;
x=n++;
x=++n; x=>5
x=>6 printf(“%d\n”, i++); 3
printf(“%d\n”, ++i); 5
Chapter 2 Types, Operators & Expressions
2.8 Increment and Decrement Operators

#include<stdio.h>
void squeeze(char s[], int c);
Example 1: void main()
/* squeeze: delete all c from { s */
void squeeze(char s[], int c)char string[]="calculating";
{ printf("%s\n", string);
int i, j; squeeze(string, 'c');
printf("%s\n", string);
for (i = j = 0; s[i] != ‘\0’; }i++)
if (s[i] != c) void squeeze(char s[], int c)
s[j++] = s[i];
{
s[j] = ‘\0’; int i, j;
} for (i = j = 0; s[i] != '\0'; i++)
if (s[i] != c)
s[j++] = s[i];
s[j] = '\0';
}
Chapter 2 Types, Operators & Expressions
2.8 Increment and Decrement Operators

s H o w a r e ‘\0’
:
Example 2: t: y o u ? ‘\0’

s H o w a r e y o u ? ‘\0’
/* strcat: concatenate t :to end of s; s must be big
enough */
void strcat(char s[], char t[])
{
int i, j;
i = j = 0;
while (s[i] != ‘\0’) /* find end of s */
i++;
while ((s[i++] = t[j++]) != ‘\0’) /*copy t*/
;
}
Chapter 2 Types, Operators & Expressions
2.9 Bitwise Operator

2.9 Bitwise Operator


 Six bitwise operators, can ONLY be applied to
ANY integer.

operator function (汉语)


& bitwise AND 按位与
| bitwise inclusive OR 按位或
^ bitwise exclusive OR 按位异或
<< left shift 左移位
>> right shift 右移位
~ one’s complement 按位取反
Chapter 2 Types, Operators & Expressions
2.9 Bitwise Operator

Bitwise operation
a b a&b a|b a^b ~a ~b
0 0 0 0 0 1 1
0 1 0 1 1 1 0
1 0 0 1 1 0 1
1 1 1 1 0 0 0

Example 1:
0000 0011
3&5=
& 0000 1001 =1
0000 0001
Chapter 2 Types, Operators & Expressions
2.9 Bitwise Operator

Bitwise AND &:


Example3:
& is often used to mask off some set of bits:
n = n & 0177;
Sets to zero all but low-order 7 bits of n.

n xxxx…xxxx X???????
&
0177 0000…0000 01111111

n 0000…0000 0???????
Chapter 2 Types, Operators & Expressions
2.9 Bitwise Operator

Bitwise inclusive OR |:
Example4:
| is used to turn bits on:
060 | 017=?
060 0011 0000
017 | 0000 1111
0011 1111
x = x | SET_ON;


If x is 1 and y is 2, then
x & y =? and x&&y=?
0 1
Chapter 2 Types, Operators & Expressions
2.9 Bitwise Operator

#include<stdio.h>
Bitwisevoid main() OR ^:
exclusive
{
if corresponding bits are the same for two operands,
int0,a=1,
the result is b=2, t; 1.
otherwise,
071 |printf("%d
052=? %d\n", a,b);
071 0011 1001
t=a; a=b; b=t;052 /*a=a^b; b=b^a;
^ 0010a=a^b;
1010*/
printf("%d %d\n", a,b); 0001 0011 (023)
}
example5: exchanges two variables’ value:
Solution1: Declares a temporary variable t and then
t=a; a=b; b=t;
Solution2: uses ^:
a=a^b; b=b^a; a=a^b;
Chapter 2 Types, Operators & Expressions
2.9 Bitwise Operator

One’s complement ~:
The unary operator ~ yields the one’s complement of
an integer; that is, it converts each 1-bit into 0-bit
and vice versa.
e.g.
025=010 101
~025=101 010

example6: x=x&~077 sets the last six bits of x to zero.


Chapter 2 Types, Operators & Expressions
2.9 Bitwise Operator

Left shift <<:


The x<<n shift the value of x left by n positions,
filling vacated bits with zero. E.g. char a;

a binary a<<1 a<<2

64 0100 0000 0 1000 0000 01 0000 0000

127 0111 1111 0 1111 1110 01 1111 1100

64<<1=0x80, 64<<2=0, 127<<1=0xfe, 127<<2=0xfc

27 26 25 24 23 22 21 20
0 1 0 0 0 0 0 0

27 26 25 24 23 22 21 20
0 1 1 1 1 1 1 1
Chapter 2 Types, Operators & Expressions
2.9 Bitwise Operator

Right shift >>:


 Right shifting an unsigned quantity always
fills vacated bits with zero.
 Right shifting a signed quantity will fill with
sign bits (arithmetic shift) on some machines
and with 0 bits (logical shift) on others.

a 1001 0111 1110 1101

a>>1: 0100 1011 1111 0110 1 (Logical shift)

a>>1: 1100 1011 1111 0110 1 (Arithmetic shift)

Precedence:
~ > << = >> > & > ^ > |
Chapter 2 Types, Operators & Expressions
2.9 Bitwise Operator

Example4: Get the n-bit field of an unsigned variable


that begins at position p. Assume that bit position 0
is at the right end.
/* getbits: get n bits from position p */
unsigned getbits (unsigned x, int p, int n)
{
return (x >> (p+1-n) ) & ~(~0 << n);
}
p 0
n p+1-n

x
p 0
n
x>>(p+1-n) xxx…………..xxx

~(~0<<n) 000..…………000 111...………………1111


&)
000..…………000
Expression
Expression
Expression

5+5
Expression
Assignment Operators
We are not
the same

Don't mix up.“=” 和“ ==”


Assignment Operators

Amount
= Value

Writing operations
Reading
are assigned values
operations can
on the right side of
be constants,
the equals sign formulas
Initial Value Assignment of Variables
Initial Value Assignment of Variables

Type variable name =


constant / expression

int iInt =
1314;
int type

iInt name

1314 constant
Examples of assignment operators

定义整型变量 i 、 j 、 k

定义整型常量 val

变量 = 常数

变量 = 表达式

变量 = 变量 = 变量 = 常量

不能赋值给常量

右值不能被赋值
Data Type Conversion
“Don't hold big things in small cups ”

Different types occupy different memory space


long
int
byte

byte < int < long


Two Conversion Modes

• Automatic conversion •Coercive


transformation
Automatic conversion

char 自动转换的兼容顺序图

byte short int long float double

byte a = 8;
int b = a;
long c = b;
double d = c;
•Coercive
transformation

语法 ( 类型名 ) 要转换的值

int a = 100;
byte b =
(byte)a;
Accuracy Loss Caused by Forced
Conversion

float f = Data misalignment


(float)3.1415926;

int i = (int)f; Loss of decimal point

byte b = Numerical overflow


(byte)129;
Chapter 2 Types, Operators & Expressions
2.10 Assignment Operators and Expressions

2.10 Assignment Operators and


Expressions
Examples:
x = 12; /* x MUST be a variable */
Compound assignment ops. op=”
+=, -=, *=, /=, %= ,<<=, >>=, &=, ^=, |=
expr1 op= expr2 <==> expr1 = (expr1) op (expr2)

 what are the equivalent


expressions for the following ones?
a+=3; a = a + 3;
x*=y+8; x = x * (y+8);
x%=3; x = x % 3;
Chapter 2 Types, Operators & Expressions
2.10 Assignment Operators and Expressions

Assignment Expressions:
<Var> <Assignment ops. > <Expressions>

can also be a assign. expr


The value of Assignment Expression is the value of
variable, i.e. the result of the calculation.

a = 3  Associate from =>


e.g.: 3 to left 
right
a = (b = 5) <==> a = b = 5 => 5
a=b=c=5 => 5
a = 5 + (c=6) => 11
a = (b=4) + (c=6) => 10
 whata is the calculation
= (b=10) / (c=2) => 5
sequence for the
expression, a += a -= a*a, ? And what is its
result when a=12 ?
Chapter 2 Types, Operators & Expressions
2.11 Condition Expression

2.11 Condition Expression


 Ternary operator: ? if (expr1)
expr2
expr1 ? expr2 : expr3
else
expr3

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

printf(“You have %d item%s.\n”, n, n==1 ? “” : “s”);


Chapter 2 Types, Operators & Expressions
2.12 Precedence and Order of Evaluation

2.12 Precedence and Order of Evaluation


OPERATORS ASSOCIATIVITY
() [] -> . left to right
! ~ ++ -- + - * & (type) sizeof right to left
* / % 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
= += -= *= \= %= &= ^= |= <<= >>= right to left
, left to right
Chapter 2 Types, Operators & Expressions
2.12 Precedence and Order of Evaluation

What difference is the following two statements?


if ( ( x & MASK ) == 0 ) is the output of this
What
if( x & MASK == 0 )
program? What is the#include<stdio.h>
output
int power(int, int);
#include<stdio.h> when using the statements:
void main()
int power(int, int); ++x; {
void main() int x=3;x));
{
printf("%d %d\n", x, power(2,
printf("%d %d\n
int x=3; }
printf("%d %d\n", ++x, power(2, x));
} int power(int base,
{
int power(int base, int n) int i;
{ int p=1;
int i; for(i=1; i<=n; i++
int p=1; p=p*base
for(i=1; i<=n; i++) return p;
p=p*base; }
return p;
}
Chapter 2 Types, Operators & Expressions
2.12 Precedence and Order of Evaluation

2.13 Mathematical library


functions
#include<math.h>
 sqrt(x)  x
 fabs(x)  | x |
 pow(x,n)  xn
 exp(x)  ex
 log(x)  ln x

You might also like