0% found this document useful (0 votes)
3 views83 pages

chapter02(1)

Uploaded by

MD HEZBULLAH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views83 pages

chapter02(1)

Uploaded by

MD HEZBULLAH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 83

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:
1. + addition, positive operator
Addition: a+b, 1+3;
Positive operator: +3, +1;
Example:
#include<stdio.h>
int main (void)
{
int a=10;
int b=20;
printf(“a+b=%d\n”, a+b); // aariable addition
printf(“a+1=%d\n”, a+1); // variable add constant
printf(“1+1=%d\n”, 1+1); // constant addition
printf(“%d\n”, +a);
printf(“%d\n”, +100);
return 0;
}
Chapter 2 Types, Operators & Expressions
2.5 Arithmetic Operators

Binary arithmetic operators:


2. - subtraction or negative operator
Subtraction: a-b, 30-10;
Negative operator: -3, -a;
Example:
#include<stdio.h>
int main (void)
{
int a=10;
int b=20;
printf(“b-a=%d\n”, b-a); // variable subtraction
printf(“a-1=%d\n”, a-1); // variable and constant subtraction
printf(“3-1=%d\n”, 3-1); // constant subtraction
printf(“%d\n”, -a);
printf(“%d\n”, -100);
return 0;
}
Chapter 2 Types, Operators & Expressions
2.5 Arithmetic Operators

Binary arithmetic operators:


3. * Multiplication operator
Since there is no × symbol on the keyboard, the c
language uses * instead.
Example:
#include<stdio.h>
int main (void)
{
int a=10;
int b=20;
printf(“b*a=%d\n”, b*a); // variable multiplication
printf(“a*1=%d\n”, a*1); // variable and constant multiplication
printf(“3*1=%d\n”, 3*1); // constant multiplication
return 0;
}
Chapter 2 Types, Operators & Expressions
2.5 Arithmetic Operators

Binary arithmetic operators:


4. / Division operator
Since there is no ÷ symbol on the keyboard, the c
language uses / instead.
Example:
#include<stdio.h>
int main (void)
{
int a=10;
int b=20;
printf(“b*a=%d\n”, b*a); // variable multiplication
printf(“a*1=%d\n”, a*1); // variable and constant multiplication
printf(“3*1=%d\n”, 3*1); // constant multiplication
return 0;
}
Chapter 2 Types, Operators & Expressions
2.5 Arithmetic Operators

Binary arithmetic operators:


5. / Remainder operator
Since there is no ÷ symbol on the keyboard, the c
language uses / instead.
Example:
#include<stdio.h>
int main (void)
{
int a=6;
int b=20;
printf(“%d\n”, b%a);
printf(“%d\n”, a%5);
printf(“%d\n”, 20%3);
printf(“%d\n”, 20%4);
return 0;
}
Chapter 2 Types, Operators & Expressions
2.6 Relational and Logical Operators

2.6 Relational and Logical Operators


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

>
>=
<
<=
==
!=
Chapter 2 Types, Operators & Expressions
2.6 Relational and Logical Operators

Relational expression
Examples:
#include<stdio.h>
int main (void)
{
int a=1>1+2;
printf(“%d\n”,a);
return 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
(3) 4&&0||2  1
(4) ‘c’ && ‘d’  1 (because ‘c’ and ‘d’ are both nonzero)
(5) 5 > 3 && 2 || 8 < 4 - !0
 5>3 && 2 || 8 < 1
 5>3 && 2 || 0
 1 && 2 || 0
 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.
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.:
Chapter 2 Types, Operators & Expressions
2.7 Type Conversion

General conversion rules:


“narrower” => “wider”
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,
float
(3) int 107 + the result of i*f ,
float
(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:
#include<stdlib.h>
#include<stdio.h>

int main()
{
char str[] = "123";
int a;
a = atoi(str); // 将字符串转化为 int 型的数字
printf("%d\n", a);
return 0;
}
Chapter 2 Types, Operators & Expressions
2.7 Type Conversion

Example 3:
/* Tolower: convert c to lower case; ASCII only */
#include <stdio.h>

int main()
{
printf("tolower('0')=%c\n", tolower('0'));
printf("tolower('a')=%c\n", tolower('a'));
printf("tolower('A')=%c\n", tolower('A'));
return 0;
}

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


are contiguous each. 
Chapter 2 Types, Operators & Expressions
2.7 Type Conversion

Explicit type conversion


(forced):
(data type)

(data type) constant;


(data type) variable;
(data type) (expression);

Example:
(double)a a’ value is converted the double type;
(int)(x+y) convert the value of x+y to int type;
(float)(5%3) convert the value of 5%3 to float type.
Chapter 2 Types, Operators & Expressions
2.7 Type Conversion


When explicit type converting, a
#include<stdio.h>medial variable is generated , and
original variable’s type is not converted
int main()
{ actually. 
float x;
int i;

x = 3.6;
i = (int)x;
printf("x=%f,i=%d\n", x, i);
return 0;
}

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.
Examples1: Examples1:
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int a=1; int a=1;
int b=0; int b=0;
b=a++; b=++a;
printf(“a=%d\n”,a); printf(“a=%d\n”,a);
printf(“b=%d\n”,b); printf(“b=%d\n”,b);
return 0; return 0;
Chapter 2 Types, Operators & Expressions
2.8 Increment and Decrement Operators

Examples2:
#include<stdio.h>
int main()
{
int a=1;
int b=a--;
printf(“a=%d\n”,a);
printf(“b=%d\n”,b);
return 0; Examples2:
} #include<stdio.h>
int main()
{
int a=1;
int b=--a;
printf(“a=%d\n”,a);
printf(“b=%d\n”,b);
return 0;
}
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 1001
9&5=
& 0000 0101 =1
0000 0001
Chapter 2 Types, Operators & Expressions
2.9 Bitwise Operator

Bitwise AND | :
Example2:

0000 1001
9|5=
| 0000 0101 =1
0000 1101
2.10 Assignment Operators and
Expressions

Expression
Expression : An expression is a
sequence of operators and opera
nds that specifies computation o
f a value Expression

5+5
Assignment Operators

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

We are not
the same
#include<stdio.h>
Assignment Operators int main()
{
1. variable = expression int a;
a=1+1 int b;
int c;
2. variable = constant a = 20;
a= 2 b = a - 10;
c = a + b;
3. variable = variable printf("a=%d\n", a);
a= b printf("b=%d\n", b);
printf("c=%d\n", c);
return 0;
}
Initial Value Assignment of Variables
Initial Value Assignment of Variables

Type variable name = constant /


expression / variable

int a = 1314;

int type

a name

13 constant
Examples of assignment operators

定义整型变量 i 、 j 、 k

定义整型常量 val

变量 = 常数

变量 = 表达式

变量 = 变量 = 变量 = 常量

不能赋值给常量

右值不能被赋值
Chapter 2 Types, Operators & Expressions
2.10 Assignment Operators and Expressions

The assignment operator has the lowest precedence


in the C language.
Examples:
c =a*10+(100%3)-b/10

Assignment Expressions:
a=1+1; a=2; a= a+1; a=b.

#include<stdio.h>
int main()
{
int a;
int b;
a = 20;
printf("a=10 the result is:%d\n", a=10);
printf("b=20+30 the result is:%d\n", b=20+30);
return 0;
}
Chapter 2 Types, Operators & Expressions
2.10 Assignment Operators and Expressions

Compound assignment oparator”


a+=10 //a=a+10
a-=10 //a=a-10
a*=10 //a=a*10
a/10 //a=a/10
a%10 //a=a%10

 what are the equivalent


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

#include<stdio.h>
int main()
{
int a=1;
int b=2;
a+= b*20;
b%= a + 10;
printf("a=%d\n", a);
printf("b=%d\n", b);
return 0;
}

Compound Assignment Expressions:


Chapter 2 Types, Operators & Expressions
2.11 Condition Expression

2.11 Condition Operator and


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

max=a>b?a:b

max=(a>b?a:b)
Chapter 2 Types, Operators & Expressions
2.10 Assignment Operators and Expressions

#include<stdio.h>
int main()
{
int a=9;
int b=0;
b = (a > 10 ? 888 : 666);
printf("b=%d\n", b);
b= (a > 5 ? 888 : 666);
printf("b=%d\n", b);
return 0;
}
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

You might also like