SlideShare a Scribd company logo
6.087 Lecture 2 – January 12, 2010
Review
Variables and data types
Operators
Epilogue
1
Review: C Programming language
• C is a fast, small,general-purpose,platform independent
programming language.
• C is used for systems programming (e.g., compilers and
interpreters, operating systems, database systems,
microcontrollers etc.)
• C is static (compiled), typed, structured and imperative.
• "C is quirky, flawed, and an enormous success."–Ritchie
1
Review: Basics
• Variable declarations: int i ; float f ;
• Intialization: char c=’A’; int x=y=10;
• Operators: +,−,∗,/,%
• Expressions: int x,y,z; x=y∗2+z∗3;
• Function: int factorial (int n); /∗function takes int , returns int ∗/
2
6.087 Lecture 2 – January 12, 2010
Review
Variables and data types
Operators
Epilogue
3
Definitions
Datatypes:
• The datatype of an object in memory determines the set
of values it can have and what operations that can be
performed on it.
• C is a weakly typed language. It allows implicit conversions
as well as forced (potentially dangerous) casting.
Operators:
• Operators specify how an object can be manipulated
(e.g.,, numeric vs. string operations).
• operators can be unary(e.g., -,++),binary (e.g.,
+,-,*,/),ternary (?:)
3
Definitions (contd.)
Expressions:
• An expression in a programming language is a
combination of values, variables, operators, and functions
Variables:
• A variable is as named link/reference to a value stored in
the system’s memory or an expression that can be
evaluated.
Consider: int x=0,y=0; y=x+2;.
• x, y are variables
• y = x + 2 is an expression
• + is an operator.
4
Variable names
Naming rules:
• Variable names can contain letters,digits and _
• Variable names should start with letters.
• Keywords (e.g., for,while etc.) cannot be used as variable
names
• Variable names are case sensitive. int x; int X declares
two different variables.
Pop quiz (correct/incorrect):
• int money$owed; (incorrect: cannot contain $)
• int total_count (correct)
• int score2 (correct)
• int 2ndscore (incorrect: must start with a letter)
• int long (incorrect: cannot use keyword)
5
Data types and sizes
C has a small family of datatypes.
• Numeric (int,float,double)
• Character (char)
• User defined (struct,union)
6
umeric data types
Depending on the precision and range required, you can use
one of the following datatypes.
signed unsigned
short short int x;short y; unsigned short x;unsigned short int y;
default int x; unsigned int x;
long long x; unsigned long x;
float float x; N/A
double double x; N/A
char char x; signed char x; unsigned char x;
• The unsigned version has roughly double the range of its
signed counterparts.
• Signed and unsigned characters differ only when used in
arithmetic expressions.
• Titbit: Flickr changed from unsigned long (2
32
− 1) to string
two years ago.
7
Big endian vs. little endian
The individual sizes are machine/compiler dependent.
However, the following is guaranteed:
sizeof(char)<sizeof(short)<=sizeof(int)<=sizeof(long) and
sizeof(char)<sizeof(short)<=sizeof(float)<=sizeof(double)
"NUXI" problem: For numeric data types that span multiple
bytes, the order of arrangement of the individual bytes is
important. Depending on the device architecture, we have "big
endian" and "little endian" formats.
8
Big endian vs. little endian (cont.)
• Big endian: the most significant bits (MSBs) occupy the
lower address. This representation is used in the powerpc
processor. Networks generally use big-endian order, and
thus it is called network order.
• Little endian : the least signficant bits (LSBs) occupy the
lower address. This representation is used on all x86
compatible processors.
Figure: (from http://en.wikipedia.org/wiki/Little_endian)
9
Constants
nts are literal/fixed values assigned to variables or used
in expressions.
atype example meaning
int i=3; i
long l=3; long
ger unsigned long ul= 3UL; unsigned long
int i=0xA; hexa
int i=012; octal
float pi=3.14159 floa
g point float pi=3.141F float
double pi=3.1415926535897932384L double
10
Constants (contd.)
Datatype example meaning
character
’A’
’x41’
’0101’
character
specified in hex
specified in octal
string
"hello world"
"hello""world"
string literal
same as "hello world"
enumeration
enum BOOL {NO,YES}
enum COLOR {R=1,G,B,Y=10}
NO=0,YES=1
G=2,B=3
11
Declarations
The general format for a declaration is
type variable-name [=value] .
Examples:
• char x; /∗ uninitialized ∗/
• char x=’A’; /∗ intialized to ’A’∗/
• char x=’A’,y=’B’; /∗multiple variables initialized ∗/
• char x=y=’Z’;/∗multiple initializations ∗/
12
Pop quiz II
• int x=017;int y=12; /∗is x>y?∗/
• short int s=0xFFFF12; /∗correct?∗/
• char c=−1;unsigned char uc=−1; /∗correct?∗/
• puts("hel"+"lo");puts("hel""lo");/∗which is correct?∗/
• enum sz{S=0,L=3,XL}; /∗what is the value of XL?∗/
• enum sz{S=0,L=−3,XL}; /∗what is the value of XL?∗/
13
6.087 Lecture 2 – January 12, 2010
Review
Variables and data types
Operators
Epilogue
14
Arithmetic operators
operator meaning examples
+ addition
x=3+2; /∗constants∗/
y+z; /∗variables∗/
x+y+2; /∗both∗/
- subtraction
3−2; /∗constants∗/
int x=y−z; /∗variables∗/
y−2−z; /∗both∗/
* multiplication
int x=3∗2; /∗constants∗/
int x=y∗z; /∗variables∗/
x∗y∗2; /∗both∗/
14
Arithmetic operators (contd.)
operator meaning examples
/ division
float x=3/2; /∗produces x=1 (int /) ∗/
float x=3.0/2 /∗produces x=1.5 (float /) ∗/
int x=3.0/2; /∗produces x=1 (int conversion)∗/
%
modulus
(remainder)
int x=3%2; /∗produces x=1∗/
int y=7;int x=y%4; /∗produces 3∗/
int y=7;int x=y%10; /∗produces 7∗/
15
Relational Operators
Relational operators compare two operands to produce a
’boolean’ result. In C any non-zero value (1 by convention) is
considered to be ’true’ and 0 is considered to be false.
operator meaning examples
> greater than
3>2; /∗evaluates to 1 ∗/
2.99>3 /∗evaluates to 0 ∗/
>=
greater than or
equal to
3>=3; /∗evaluates to 1 ∗/
2.99>=3 /∗evaluates to 0 ∗/
< lesser than
3<3; /∗evaluates to 0 ∗/
’A’<’B’/∗evaluates to 1∗/
<=
lesser than or equal
to
3<=3; /∗evaluates to 1 ∗/
3.99<3 /∗evaluates to 0 ∗/
16
Relational Operators
Testing equality is one of the most commonly used relational
operator
==
operator.
!=
Gotchas:
meaning
equal to
not equal to
examples
3==3; /∗evaluates to 1 ∗/
’A’==’a’/∗evaluates to 0 ∗/
3!=3; /∗evaluates to 0 ∗/
2.99!=3 /∗evaluates to 1 ∗/
• Note that the "==" equality operator is different from the
"=", assignment operator.
• Note that the "==" operator on float variables is tricky
because of finite precision.
17
Logical operators
operator meaning examples
&& AND
((9/3)==3) && (2∗3==6); /∗evaluates to 1 ∗/
(’A’==’a’) && (3==3) /∗evaluates to 0 ∗/
|| OR
2==3 || ’A’==’A’; /∗evaluates to 1 ∗/
2.99>=3 || 0 /∗evaluates to 0 ∗/
! NOT
!(3==3); /∗evaluates to 0 ∗/
!(2.99>=3) /∗evaluates to 1 ∗/
Short circuit: The evaluation of an expression is discontinued if
the value of a conditional expression can be determined early.
Be careful of any side effects in the code.
Examples:
• (3==3) || ((c=getchar())==’y’). The second expression is not
evaluated.
• (0) && ((x=x+1)>0) . The second expression is not evaluated.
18
Increment and decrement operators
Increment and decrement are common arithmetic operation. C
provides two short cuts for the same.
Postfix
• x++ is a short cut for x=x+1
• x−− is a short cut for x=x−1
• y=x++ is a short cut for y=x;x=x+1. x is evaluated before it is
incremented.
• y=x−− is a short cut for y=x;x=x−1. x is evaluated before it is
decremented.
19
Increment and decrement operators
Prefix:
• ++x is a short cut for x=x+1
• −−x is a short cut for x=x−1
• y=++x is a short cut for x=x+1;y=x;. x is evaluate after it is
incremented.
• y=−−x is a short cut for x=x−1;y=x;. x is evaluate after it is
decremented.
20
Bitwise Operators
operator meaning examples
& AND
0x77 & 0x3; /∗evaluates to 0x3 ∗/
0x77 & 0x0; /∗evaluates to 0 ∗/
| OR
0x700 | 0x33; /∗evaluates to 0x733 ∗/
0x070 | 0 /∗evaluates to 0x070 ∗/
ˆ XOR
0x770 ^ 0x773; /∗evaluates to 0x3 ∗/
0x33 ^ 0x33; /∗evaluates to 0 ∗/
« left shift
0x01<<4; /∗evaluates to 0x10 ∗/
1<<2; /∗evaluates to 4 ∗/
» right shift
0x010>>4; /∗evaluates to 0x01 ∗/
4>>1 /∗evaluates to 2 ∗/
Notes:
• AND is true only if both operands are true.
• OR is true if any operand is true.
• XOR is true if only one of the operand is true.
21
Assignment Operators
Another common expression type found while programming in
C is of the type var = var (op) expr
• x=x+1
• x=x∗10
• x=x/2
C provides compact assignment operators that can be used
instead.
• x+=1 /∗is the same as x=x+1∗/
• x−=1 /∗is the same as x=x−1∗/
• x∗=10 /∗is the same as x=x∗10 ∗/
• x/=2 /∗ is the same as x=x/2
• x%=2 /∗is the same as x=x%2
22
Conditional Expression
A common pattern in C (and in most programming) languages
is the following:
i f ( cond )
x=<expra >;
else
x=<exprb >;
C provides syntactic sugar to express the same using the
ternary operator ’?:’
sign=x>0?1:−1; isodd=x%2==1?1:0;
i f ( x >0) i f ( x%2==1)
sign =1 isodd=1
else else
sign=−1 isodd=0
Notice how the ternary operator makes the code shorter and
easier to understand (syntactic sugar).
23
6.087 Lecture 2 – January 12, 2010
Review
Variables and data types
Operators
Epilogue
24
Type Conversions
When variables are promoted to higher precision, data is
preserved. This is automatically done by the compiler for mixed
data type expressions.
int i ;
fl oa t f ;
f = i +3.14159; / ∗ i i s promoted to f l o a t , f =( f l o a t ) i +3.14159 ∗ /
Another conversion done automatically by the compiler is ’char’
→ ’int’. This allows comparisons as well as manupilations of
character variables.
isupper =(c>=’A’ && c<=’Z’ )? 1: 0 ; / ∗ c and l i t e r a l constants
are converted to i n t ∗ /
i f ( ! isupper )
c=c−’a’+’A’ ; / ∗ subtrac tio n i s possible
because of intege r conversion ∗ /
As a rule (with exceptions), the compiler promotes each term in
an binary expression to the highest precision operand.
24
Precedence and Order of Evaluation
• ++,–,(cast),sizeof have the highest priority
• *,/,% have higher priority than +,
• ==,!= have higher priority than &&,||
• assignment operators have very low priority
Use () generously to avoid ambiguities or side effects
associated with precendence of operators.
• y=x∗3+2 /∗same as y=(x∗3)+2∗/
• x!=0 && y==0 /∗same as (x!=0) && (y==0)∗/
• d= c>=’0’&& c<=’9’/∗same as d=(c>=’0’) && (c<=’9’)∗/
25
MIT OpenCourseWare
http://ocw.mit.edu
6.087 Practical Programming in C
IAP 2010
For information about citing these materials or our Terms of Use,visit: http://ocw.mit.edu/terms.

More Related Content

PDF
Mit6 087 iap10_lec02
PDF
Module 2_PPT_P1 POP Notes module 2 fdfd.pdf
PPTX
Chapter 2: Elementary Programming
PPT
Token and operators
PPTX
PDF
Lamborghini Veneno Allegheri #2004@f**ck
PDF
02 - Data Types and Expressions using C.pdf
PPTX
additional.pptx
Mit6 087 iap10_lec02
Module 2_PPT_P1 POP Notes module 2 fdfd.pdf
Chapter 2: Elementary Programming
Token and operators
Lamborghini Veneno Allegheri #2004@f**ck
02 - Data Types and Expressions using C.pdf
additional.pptx

Similar to Lecture 02 Programming C for Beginners 001 (20)

PPTX
BCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptx
PPTX
B.sc CSIT 2nd semester C++ Unit2
PPT
c_tutorial_2.ppt
PPTX
data type.pptxddddswwyertr hai na ki extend kr de la
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
PPT
C tutorial
PPT
PPTX
introduction to c programming and C History.pptx
PPTX
PDF
Fundamentals C programming and strong your skills.
PPTX
presentation_c_basics_1589366177_381682.pptx
PPTX
Chapter1.pptx
PPTX
C programinng
PPT
02a fundamental c++ types, arithmetic
PPTX
C_Programming_Language_tutorial__Autosaved_.pptx
PPTX
Learn C LANGUAGE at ASIT
PPTX
Review of C programming language.pptx...
PDF
2nd PUC Computer science chapter 5 review of c++
PPT
C program
PPT
Csharp4 operators and_casts
BCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptx
B.sc CSIT 2nd semester C++ Unit2
c_tutorial_2.ppt
data type.pptxddddswwyertr hai na ki extend kr de la
03 and 04 .Operators, Expressions, working with the console and conditional s...
C tutorial
introduction to c programming and C History.pptx
Fundamentals C programming and strong your skills.
presentation_c_basics_1589366177_381682.pptx
Chapter1.pptx
C programinng
02a fundamental c++ types, arithmetic
C_Programming_Language_tutorial__Autosaved_.pptx
Learn C LANGUAGE at ASIT
Review of C programming language.pptx...
2nd PUC Computer science chapter 5 review of c++
C program
Csharp4 operators and_casts
Ad

More from MahmoudElsamanty (7)

PPTX
Lecture 04 Programming C for Beginners 001
PPTX
Lecture 03 Programming C for Beginners 001
PPTX
Lecture 01 Programming C for Beginners 001
PPTX
lecture03_EmbeddedSoftware for Beginners
PPTX
ECE-3567-Lecture-2-Spring-2025 for beginners
PPTX
ECE-3567-Lecture-1-Spring-2025 for beginner
PPTX
C Programming course for beginners and intermideate
Lecture 04 Programming C for Beginners 001
Lecture 03 Programming C for Beginners 001
Lecture 01 Programming C for Beginners 001
lecture03_EmbeddedSoftware for Beginners
ECE-3567-Lecture-2-Spring-2025 for beginners
ECE-3567-Lecture-1-Spring-2025 for beginner
C Programming course for beginners and intermideate
Ad

Recently uploaded (20)

PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPT
Project quality management in manufacturing
PPTX
additive manufacturing of ss316l using mig welding
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
UNIT 4 Total Quality Management .pptx
DOCX
573137875-Attendance-Management-System-original
PPTX
Sustainable Sites - Green Building Construction
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
Arduino robotics embedded978-1-4302-3184-4.pdf
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Project quality management in manufacturing
additive manufacturing of ss316l using mig welding
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
CH1 Production IntroductoryConcepts.pptx
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Lecture Notes Electrical Wiring System Components
UNIT 4 Total Quality Management .pptx
573137875-Attendance-Management-System-original
Sustainable Sites - Green Building Construction
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Internet of Things (IOT) - A guide to understanding
Model Code of Practice - Construction Work - 21102022 .pdf

Lecture 02 Programming C for Beginners 001

  • 1. 6.087 Lecture 2 – January 12, 2010 Review Variables and data types Operators Epilogue 1
  • 2. Review: C Programming language • C is a fast, small,general-purpose,platform independent programming language. • C is used for systems programming (e.g., compilers and interpreters, operating systems, database systems, microcontrollers etc.) • C is static (compiled), typed, structured and imperative. • "C is quirky, flawed, and an enormous success."–Ritchie 1
  • 3. Review: Basics • Variable declarations: int i ; float f ; • Intialization: char c=’A’; int x=y=10; • Operators: +,−,∗,/,% • Expressions: int x,y,z; x=y∗2+z∗3; • Function: int factorial (int n); /∗function takes int , returns int ∗/ 2
  • 4. 6.087 Lecture 2 – January 12, 2010 Review Variables and data types Operators Epilogue 3
  • 5. Definitions Datatypes: • The datatype of an object in memory determines the set of values it can have and what operations that can be performed on it. • C is a weakly typed language. It allows implicit conversions as well as forced (potentially dangerous) casting. Operators: • Operators specify how an object can be manipulated (e.g.,, numeric vs. string operations). • operators can be unary(e.g., -,++),binary (e.g., +,-,*,/),ternary (?:) 3
  • 6. Definitions (contd.) Expressions: • An expression in a programming language is a combination of values, variables, operators, and functions Variables: • A variable is as named link/reference to a value stored in the system’s memory or an expression that can be evaluated. Consider: int x=0,y=0; y=x+2;. • x, y are variables • y = x + 2 is an expression • + is an operator. 4
  • 7. Variable names Naming rules: • Variable names can contain letters,digits and _ • Variable names should start with letters. • Keywords (e.g., for,while etc.) cannot be used as variable names • Variable names are case sensitive. int x; int X declares two different variables. Pop quiz (correct/incorrect): • int money$owed; (incorrect: cannot contain $) • int total_count (correct) • int score2 (correct) • int 2ndscore (incorrect: must start with a letter) • int long (incorrect: cannot use keyword) 5
  • 8. Data types and sizes C has a small family of datatypes. • Numeric (int,float,double) • Character (char) • User defined (struct,union) 6
  • 9. umeric data types Depending on the precision and range required, you can use one of the following datatypes. signed unsigned short short int x;short y; unsigned short x;unsigned short int y; default int x; unsigned int x; long long x; unsigned long x; float float x; N/A double double x; N/A char char x; signed char x; unsigned char x; • The unsigned version has roughly double the range of its signed counterparts. • Signed and unsigned characters differ only when used in arithmetic expressions. • Titbit: Flickr changed from unsigned long (2 32 − 1) to string two years ago. 7
  • 10. Big endian vs. little endian The individual sizes are machine/compiler dependent. However, the following is guaranteed: sizeof(char)<sizeof(short)<=sizeof(int)<=sizeof(long) and sizeof(char)<sizeof(short)<=sizeof(float)<=sizeof(double) "NUXI" problem: For numeric data types that span multiple bytes, the order of arrangement of the individual bytes is important. Depending on the device architecture, we have "big endian" and "little endian" formats. 8
  • 11. Big endian vs. little endian (cont.) • Big endian: the most significant bits (MSBs) occupy the lower address. This representation is used in the powerpc processor. Networks generally use big-endian order, and thus it is called network order. • Little endian : the least signficant bits (LSBs) occupy the lower address. This representation is used on all x86 compatible processors. Figure: (from http://en.wikipedia.org/wiki/Little_endian) 9
  • 12. Constants nts are literal/fixed values assigned to variables or used in expressions. atype example meaning int i=3; i long l=3; long ger unsigned long ul= 3UL; unsigned long int i=0xA; hexa int i=012; octal float pi=3.14159 floa g point float pi=3.141F float double pi=3.1415926535897932384L double 10
  • 13. Constants (contd.) Datatype example meaning character ’A’ ’x41’ ’0101’ character specified in hex specified in octal string "hello world" "hello""world" string literal same as "hello world" enumeration enum BOOL {NO,YES} enum COLOR {R=1,G,B,Y=10} NO=0,YES=1 G=2,B=3 11
  • 14. Declarations The general format for a declaration is type variable-name [=value] . Examples: • char x; /∗ uninitialized ∗/ • char x=’A’; /∗ intialized to ’A’∗/ • char x=’A’,y=’B’; /∗multiple variables initialized ∗/ • char x=y=’Z’;/∗multiple initializations ∗/ 12
  • 15. Pop quiz II • int x=017;int y=12; /∗is x>y?∗/ • short int s=0xFFFF12; /∗correct?∗/ • char c=−1;unsigned char uc=−1; /∗correct?∗/ • puts("hel"+"lo");puts("hel""lo");/∗which is correct?∗/ • enum sz{S=0,L=3,XL}; /∗what is the value of XL?∗/ • enum sz{S=0,L=−3,XL}; /∗what is the value of XL?∗/ 13
  • 16. 6.087 Lecture 2 – January 12, 2010 Review Variables and data types Operators Epilogue 14
  • 17. Arithmetic operators operator meaning examples + addition x=3+2; /∗constants∗/ y+z; /∗variables∗/ x+y+2; /∗both∗/ - subtraction 3−2; /∗constants∗/ int x=y−z; /∗variables∗/ y−2−z; /∗both∗/ * multiplication int x=3∗2; /∗constants∗/ int x=y∗z; /∗variables∗/ x∗y∗2; /∗both∗/ 14
  • 18. Arithmetic operators (contd.) operator meaning examples / division float x=3/2; /∗produces x=1 (int /) ∗/ float x=3.0/2 /∗produces x=1.5 (float /) ∗/ int x=3.0/2; /∗produces x=1 (int conversion)∗/ % modulus (remainder) int x=3%2; /∗produces x=1∗/ int y=7;int x=y%4; /∗produces 3∗/ int y=7;int x=y%10; /∗produces 7∗/ 15
  • 19. Relational Operators Relational operators compare two operands to produce a ’boolean’ result. In C any non-zero value (1 by convention) is considered to be ’true’ and 0 is considered to be false. operator meaning examples > greater than 3>2; /∗evaluates to 1 ∗/ 2.99>3 /∗evaluates to 0 ∗/ >= greater than or equal to 3>=3; /∗evaluates to 1 ∗/ 2.99>=3 /∗evaluates to 0 ∗/ < lesser than 3<3; /∗evaluates to 0 ∗/ ’A’<’B’/∗evaluates to 1∗/ <= lesser than or equal to 3<=3; /∗evaluates to 1 ∗/ 3.99<3 /∗evaluates to 0 ∗/ 16
  • 20. Relational Operators Testing equality is one of the most commonly used relational operator == operator. != Gotchas: meaning equal to not equal to examples 3==3; /∗evaluates to 1 ∗/ ’A’==’a’/∗evaluates to 0 ∗/ 3!=3; /∗evaluates to 0 ∗/ 2.99!=3 /∗evaluates to 1 ∗/ • Note that the "==" equality operator is different from the "=", assignment operator. • Note that the "==" operator on float variables is tricky because of finite precision. 17
  • 21. Logical operators operator meaning examples && AND ((9/3)==3) && (2∗3==6); /∗evaluates to 1 ∗/ (’A’==’a’) && (3==3) /∗evaluates to 0 ∗/ || OR 2==3 || ’A’==’A’; /∗evaluates to 1 ∗/ 2.99>=3 || 0 /∗evaluates to 0 ∗/ ! NOT !(3==3); /∗evaluates to 0 ∗/ !(2.99>=3) /∗evaluates to 1 ∗/ Short circuit: The evaluation of an expression is discontinued if the value of a conditional expression can be determined early. Be careful of any side effects in the code. Examples: • (3==3) || ((c=getchar())==’y’). The second expression is not evaluated. • (0) && ((x=x+1)>0) . The second expression is not evaluated. 18
  • 22. Increment and decrement operators Increment and decrement are common arithmetic operation. C provides two short cuts for the same. Postfix • x++ is a short cut for x=x+1 • x−− is a short cut for x=x−1 • y=x++ is a short cut for y=x;x=x+1. x is evaluated before it is incremented. • y=x−− is a short cut for y=x;x=x−1. x is evaluated before it is decremented. 19
  • 23. Increment and decrement operators Prefix: • ++x is a short cut for x=x+1 • −−x is a short cut for x=x−1 • y=++x is a short cut for x=x+1;y=x;. x is evaluate after it is incremented. • y=−−x is a short cut for x=x−1;y=x;. x is evaluate after it is decremented. 20
  • 24. Bitwise Operators operator meaning examples & AND 0x77 & 0x3; /∗evaluates to 0x3 ∗/ 0x77 & 0x0; /∗evaluates to 0 ∗/ | OR 0x700 | 0x33; /∗evaluates to 0x733 ∗/ 0x070 | 0 /∗evaluates to 0x070 ∗/ ˆ XOR 0x770 ^ 0x773; /∗evaluates to 0x3 ∗/ 0x33 ^ 0x33; /∗evaluates to 0 ∗/ « left shift 0x01<<4; /∗evaluates to 0x10 ∗/ 1<<2; /∗evaluates to 4 ∗/ » right shift 0x010>>4; /∗evaluates to 0x01 ∗/ 4>>1 /∗evaluates to 2 ∗/ Notes: • AND is true only if both operands are true. • OR is true if any operand is true. • XOR is true if only one of the operand is true. 21
  • 25. Assignment Operators Another common expression type found while programming in C is of the type var = var (op) expr • x=x+1 • x=x∗10 • x=x/2 C provides compact assignment operators that can be used instead. • x+=1 /∗is the same as x=x+1∗/ • x−=1 /∗is the same as x=x−1∗/ • x∗=10 /∗is the same as x=x∗10 ∗/ • x/=2 /∗ is the same as x=x/2 • x%=2 /∗is the same as x=x%2 22
  • 26. Conditional Expression A common pattern in C (and in most programming) languages is the following: i f ( cond ) x=<expra >; else x=<exprb >; C provides syntactic sugar to express the same using the ternary operator ’?:’ sign=x>0?1:−1; isodd=x%2==1?1:0; i f ( x >0) i f ( x%2==1) sign =1 isodd=1 else else sign=−1 isodd=0 Notice how the ternary operator makes the code shorter and easier to understand (syntactic sugar). 23
  • 27. 6.087 Lecture 2 – January 12, 2010 Review Variables and data types Operators Epilogue 24
  • 28. Type Conversions When variables are promoted to higher precision, data is preserved. This is automatically done by the compiler for mixed data type expressions. int i ; fl oa t f ; f = i +3.14159; / ∗ i i s promoted to f l o a t , f =( f l o a t ) i +3.14159 ∗ / Another conversion done automatically by the compiler is ’char’ → ’int’. This allows comparisons as well as manupilations of character variables. isupper =(c>=’A’ && c<=’Z’ )? 1: 0 ; / ∗ c and l i t e r a l constants are converted to i n t ∗ / i f ( ! isupper ) c=c−’a’+’A’ ; / ∗ subtrac tio n i s possible because of intege r conversion ∗ / As a rule (with exceptions), the compiler promotes each term in an binary expression to the highest precision operand. 24
  • 29. Precedence and Order of Evaluation • ++,–,(cast),sizeof have the highest priority • *,/,% have higher priority than +, • ==,!= have higher priority than &&,|| • assignment operators have very low priority Use () generously to avoid ambiguities or side effects associated with precendence of operators. • y=x∗3+2 /∗same as y=(x∗3)+2∗/ • x!=0 && y==0 /∗same as (x!=0) && (y==0)∗/ • d= c>=’0’&& c<=’9’/∗same as d=(c>=’0’) && (c<=’9’)∗/ 25
  • 30. MIT OpenCourseWare http://ocw.mit.edu 6.087 Practical Programming in C IAP 2010 For information about citing these materials or our Terms of Use,visit: http://ocw.mit.edu/terms.