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

Week5 Combine

The document discusses functions in C/C++ programming. It explains that functions allow programmers to break complex problems down into smaller, more manageable subtasks or algorithms. This procedural abstraction or divide-and-conquer approach makes programs easier to design, implement, test and maintain. Functions in C are independent building blocks that take input, perform some processing, and return output. Well-organized C programs group related functions into source code files.

Uploaded by

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

Week5 Combine

The document discusses functions in C/C++ programming. It explains that functions allow programmers to break complex problems down into smaller, more manageable subtasks or algorithms. This procedural abstraction or divide-and-conquer approach makes programs easier to design, implement, test and maintain. Functions in C are independent building blocks that take input, perform some processing, and return output. Well-organized C programs group related functions into source code files.

Uploaded by

raley
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 123

HIGH-LEVEL PROGRAMMING I

Comma operator by Prasanna Ghali


Comma Operator: Syntax (1/2)
2

 Allows “gluing” of multiple expressions into


single expression
 Syntax: expression , expression
1 2
Comma Operator: Syntax (2/2)
3

 Syntax: expression1, expression2


 “Fully evaluate expression1, then evaluate
expression2“
 Type and value of entire expression is type and
value of rightmost expression expression2
 This means that both expression1 and
expression2 must have same type
 Bottom of precedence table, L-R associative
Comma Operator: Exercise (1/2)
4

 What are the values of int variables i, j


and k after execution of each of following
expressions?
 For each expression, assume i is 0 and j is 5

Expression i j k
i++, j = j + i -
++i, i = j + i -
i = 1, j = 2, k = ++i+j
Comma Operator: Exercise (2/2)
5

 What are the values of int variables i, j


and k after execution of each of following
expressions?
 For each expression, assume i is 0 and j is 5

Expression i j k
i++, j = j + i 1 6 -
++i, i = j + i 6 5 -
i = 1, j = 2, k = ++i+j 2 2 4
Comma Operator in for
6
Statements
 Most often used in for statements
 Allows multiple assignment expressions to be
combined into single expression for purpose of
initializing multiple variables when entering for
loop

for (x = 0, y = N; x<N && y>0; ++x,--y) {


/* statements */
}
Comma Operator: Example 1
7

for (int i=0, j=0; i<16 || j<8; i+=2, j++) {


printf("%2d * %d = %2d\n", i, j, i*j);
}

0 * 0 = 0
2 * 1 = 2
4 * 2 = 8
6 * 3 = 18
8 * 4 = 32
10 * 5 = 50
12 * 6 = 72
14 * 7 = 98
Comma Operator: Exercises (1/2)
8

 What are the values of int variables i, j


and k after execution of each of following
expressions?
 For each expression, assume i is 5 and j is 3

Expression c i j
c = i++, ++j, j + i
c = (i++, ++j), j + i
c = (++i, ++j, j + i)
Comma Operator: Exercises (2/2)
9

 What are the values of int variables i, j


and k after execution of each of following
expressions?
 For each expression, assume i is 5 and j is 3

Expression c i j
c = i++, ++j, j + i; 5 6 4
c = (i++, ++j), j + i; 4 6 4
c = (++i, ++j, j + i); 10 6 4
HIGH-LEVEL PROGRAMMING I
do-while loop by Prasanna Ghali
Pretest Loops: while and for
2
Statements
 while and for statements called pretest loops
because statement executed only if loop
condition is true

int i = 0;
while (i <= 20) {
printf("%d ", i);
i += 5;
}

output for (int i = 0; i <= 20; i += 5) {


printf("%d ", i);
0 5 10 15 20
}
do...while Loop Structure
3

 Called posttest loop because


condition evaluated after executing
statement loop body
true  Useful in scenarios where
expression statement must be executed at
least once
false

do
statement
while(expression);
do...while and while:
Comparison

statement

true true
expression expression statement

false false

do
statement while(expression)
while(expression); statement
do...while Loop Structure:
5
Example 1
int i = 0; int i = 0;
while (i <= 20) { do {
printf("%d ", i); printf("%d ", i);
i += 5; i += 5;
} } while (i <= 20);

0 5 10 15 20 for (int i = 0; i <= 20; i += 5) {


printf("%d ", i);
}
do...while Loop Structure:
6
Example 2
int i = 11; int i = 11;
while (i <= 10) { do {
printf("%d ", i); printf("%d ", i);
i += 5; i += 5;
} } while (i <= 10);

? ?
do...while Loop Structure:
7
Example 3
 do…while is often used for input validation
 Here, user required to enter a number between
30 and 60

int score = 0;
do {
printf("Enter value between 30 and 60: ");
scanf("%d", &score);
} while (score < 30 || score > 60);
// guaranteed that score is between 30 and 60
do...while Loop Structure:
8
Example 4
 do…while is often used for input validation
 Here, user required to enter lowercase Latin
character

char ch = '\0';
do {
printf("Enter lowercase Latin character: ");
scanf("%c%*c", &ch);
} while (ch < 'a' || ch > 'z');
// guaranteed that ch is between 'a' and 'z'
HIGH-LEVEL PROGRAMMING I
Functions by Prasanna Ghali
References
2

 Chapter 7 of the text book


Consider Complex Problem
3

 You have to send flowers to your grandmother


(who lives in Japan) for her birthday
 Plant flowers
 Water flowers
 Pick flowers
 Fly to Japan with flowers
Another Complex Problem
4

 You’re asked to organize catering for a


wedding
 Make up guest list
 Invite guests
 Select appropriate menu
 Book reception hall
 …
Another Complex Problem
5

 You’re asked to organize catering for a wedding


 Make up guest list
 Get list from groom
 Get list from bride
 Check for conflicts
 Check with bride about groom’s list
 Check with groom about bride’s list
 Check final list with groom’s parents
 Check final list with bride’s parents
 …
 Invite guests
 …
 Select appropriate menu
 Book reception hall
 …
Procedural Programming Paradigm
6
(1/2)
 Breaking down tasks into smaller subtasks is
good plan of attack for solving complex
programming problems too
 Each “large” task is decomposed into smaller
subtasks and so forth
 Process is continued until subtask can be
implemented by single algorithm
 Synonyms for this strategy: top-down design,
procedural abstraction, functional decomposition,
divide-and-conquer, stepwise refinement
Procedural Programming Paradigm
7
(2/2)
 In C/C++, algorithm is packaged into building
block called function
 Other languages refer to function as procedure or
subroutine or method
 Program is organized into these smaller,
independent units called functions

Input 1 I’m a function


⋮ Output
Input n (algorithm)
Advantages of Functions
8

 Divide and conquer approach to complexity


 Divide complicated whole into simpler and more
manageable units
 Standalone, independent functions are easier to understand,
implement, maintain, test and debug
 Cost and pace of development
 Different people can work on different functions
simultaneously
 Building blocks for programs
 Write function once and use it many times in same program
or many other programs
Organization of C Programs (1/2)
9

source-file-1.c source-file-2.c source-file-3.c


function A
function main

function C
call function A

function B
call function B

call function C

 Every C program must have one and only one


function called main not a C/C++ keyword!!!
Organization of C Programs (2/2)
10

 Related functions are organized into a source file


 Think of C program as one or more source files
with each source file containing one or more
related functions
// source-file-1.c // source-file-n.c
preprocessing directives preprocessing directives

function prototypes/declarations function prototypes/declarations

data declarations (global) data declarations (global)

return-type return-type
main (parameter declarations)
⋯ function-name (parameter declarations)
{ {
data declarations (local) data declarations (local)
statements statements
} }

other functions other functions


Function Prototype/Declaration
11

 To use particular function in your program,


function prototype (in C) or function declaration
(in C++) must be known:
 Name of function
 Number of inputs – each input is called parameter
 Data type of each parameter
 Data type of function - type of value returned by
function // somewhere in math.h
double sqrt(double);
this line is called function prototype in
C and function declaration in C++
General Syntax of Function
12
Prototype or Declaration

function-return-type function-name(parameter-list);

double area(double width, double height);


int volume(int width, int height, int depth);
double cube(double);
Function Definition (1/2)
13

 To use particular function in your program, function


prototype (in C) or function declaration (in C++)
must be known:
 Name of function
 Number of inputs – each input is called parameter
 Data type of each parameter
 Data type of function - the type of value returned by
function
 One more thing is required during linking to
generate executable – the code that will
implement the algorithm encapsulated by function
Function Definition (2/2)
14

function definition = function prototype + code

return-type function-name(parameter-list)
{
statements
}

this variable is called formal parameter or just parameter


int myabs(int number) {
return number < 0 ? -number : number;
}
Parts of Function Definition
15

function name parameters


comma to separate
function return type parameters
int max(int x, int y)
{
int large; parameter list

if (x > y) {
large = x; local variable that is
function body } else { alive only during the
large = y; execution of this
}
function
return large;
} function return value
Function Call Operator
16

Prototype of function () is called function call operator


sqrt is in <math.h>
#include <stdio.h>
#include <math.h>

int main(void) {
double value = 9.0;
double root = sqrt(value);
printf("Root of %f is %f\n", value, root);
return 0;
}

function name this expression is called function argument


Will Program Compile? Link? (1/3)
17

In C, compiler will assume


#include <stdio.h> average is function that
takes unknown number of
int main(void) { parameters and returns an
double x = 10.0, y = 20.0; int value.
double z = average(x, y);
However, C++ compiler
printf("Average is: %d\n", z); will not make any such
return 0; assumptions and simply
} flag an error!!!
To make C compiler
double
behave as C++ compiler,
average(double x, double y) {
return (x+y)/2.0; we’ll use options –Wstrict-
} prototypes and
–pedantic-errors!!!
Will Program Compile? Link? (2/3)
18

#include <stdio.h>
This is function declaration!!!
double
average(double x, double y); In both C and C++,
compiler will compile this
int main(void) { source file because it
double x = 10.0, y = 20.0;
double z = average(x, y);
finds a declaration for
this function.
printf("Average is: %d\n", z); However, the linker will
return 0; flag an error because the
} definition of function
average is not present!!!
Will Program Compile? Link? (3/3)
19

#include <stdio.h> Every function definition is


also a declaration!!!
double
average(double x, double y) {
return (x+y)/2.0;
} In both C and C++, compiler
will compile this source file
int main(void) { because it finds a
double x = 10.0, y = 20.0; declaration for this function.
double z = average(x, y);
The linker will generate an
printf("Average is: %d\n", z); executable since it can find
return 0; the definition for function
} average!!!
Examples
20

// no return, no parameters
// return, no parameters void say_hello(void) {
double pi(void) { printf("Hello!!!\n");
return 3.14159; return; // optional
} }

// no return, 1 parameter
void say_hello_alot(int count) {
for (int i = 0; i < count; ++i) {
printf("Hello!!!\n");
}
// return statement is optional since
// function is returning void
}
Calling Functions
21

void say_hello(void); // defined in previous slide


void say_hello_alot(int); // defined in previous slide
double pi(void); // defined in previous slide

int main(void) {
say_hello(); // ok: say_hello has no arguments
// parentheses represent function call operator
say_hello_alot(5); // ok: one argument
double d = pi()+56.0; // ok: pi has no arguments
pi(); // ok: caller can ignore return
// value from function
d = pi; // error: function call operator is required!!!
pi; // ok: pi without function call operator
// means “pointer to function pi”
// more on pointers later ...
d = say_hello(); // error: say_hello has no return value!!!
return 0;
}
Program Memory (1/2)
22

text area consists of machine


text area language code for every function
present in executable.

heap Programs make use of stack to


Increasing
(details for this section support function call mechanism.
address
in future lectures!!!) Machine uses stack to pass
arguments, return values, provide
storage for local variables in
functions, and save registers for
stack later restoration.
Portion of stack allocated for single
function call is called stack frame.
Program Memory (2/2)
23

 C/C++ function call mechanism is


implemented by machine using portion of
program memory called stack
 Stack is program memory used for inter-function
communication: passing arguments, for storing
return value, for saving registers
 Stack is also used for providing storage for
variables defined in a function
 Portion of stack allocated for single function is
called stack frame
Functions: Pass-by-Value Convention
24
(1/20)
this variable is called formal parameter or just parameter
int myabs(int number) {
return number < 0 ? -number : number;
}

client calls function myabs using function call operator ()


int num = 10; this expression is called function argument
num = myabs(-num)
1) At runtime, expression (or argument) -num is evaluated
2) Result of evaluation is used to initialize parameter number
3) Changes made to parameter number are localized to function myabs
4) Function myabs terminates by returning value of type int
5) When function myabs terminates, variable number ceases to exist
Functions: Pass-by-Value Convention
25
(2/20)
 Example  Output
#include <stdio.h>
Before call: i is 5
void foo(int x) {
printf("In foo, x is %d\n", x);
In foo, x is 5
x = 10; In foo, x is now 10
printf("In foo, x is now %d\n", x); After call: i is 5
}

int main(void) {
int i;
i = 5;
printf("Before call: i is %d\n", i);
foo(i); // call to function foo
printf("After call: i is %d\n", i);
return 0;
}
Functions: Pass-by-Value Convention
26
(3/20)

#include <stdio.h>

void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
}

int main(void) {
int i;
i = 5;
printf("Before call: i is %d\n", i);
foo(i); // call to function foo
printf("After call: i is %d\n", i); main
return 0; stack frame
i ?
}
Functions: Pass-by-Value Convention
27
(4/20)

#include <stdio.h>

void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
}

int main(void) {
int i;
i = 5;
printf("Before call: i is %d\n", i);
foo(i); // call to function foo
printf("After call: i is %d\n", i); main
return 0; stack frame
i 5
}
Functions: Pass-by-Value Convention
28
(5/20)

#include <stdio.h>

void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
}

int main(void) {
int i;
i = 5;
printf("Before call: i is %d\n", i);
foo(i); // call to function foo
printf("After call: i is %d\n", i); ? ? main
return 0; stack frame
i 5
}
Functions: Pass-by-Value Convention
29
(6/20)

#include <stdio.h>

void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
}

int main(void) {
int i;
i = 5;
printf("Before call: i is %d\n", i);
foo(i); // call to function foo
printf("After call: i is %d\n", i); str 5 main
return 0; stack frame
i 5
}
Functions: Pass-by-Value Convention
30
(7/20)
Before call: i is 5

#include <stdio.h>

void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x); local variables
} in function printf

int main(void) {
int i; printf
var1 var2
i = 5; stack frame
printf("Before call: i is %d\n", i); p str q 5
foo(i); // call to function foo
printf("After call: i is %d\n", i); str 5 main
return 0; stack frame
i 5
}
Functions: Pass-by-Value Convention
31
(8/20)
Before call: i is 5

#include <stdio.h>

void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
}

int main(void) {
int i;
i = 5;
printf("Before call: i is %d\n", i);
foo(i); // call to function foo
printf("After call: i is %d\n", i); ? main
return 0; stack frame
i 5
}
Functions: Pass-by-Value Convention
32
(9/20)
Before call: i is 5

#include <stdio.h>

void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
}

int main(void) {
int i;
i = 5;
printf("Before call: i is %d\n", i);
foo(i); // call to function foo
printf("After call: i is %d\n", i); 5 main
return 0; stack frame
i 5
}
Functions: Pass-by-Value Convention
33
(10/20)
Before call: i is 5

#include <stdio.h>

void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
}

int main(void) {
int i; foo
i = 5; stack frame
printf("Before call: i is %d\n", i); x 5
foo(i); // call to function foo
printf("After call: i is %d\n", i); 5 main
return 0; stack frame
i 5
}
Functions: Pass-by-Value Convention
34
(11/20)
Before call: i is 5
In foo, x is 5
#include <stdio.h>

void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
} var1 var2 printf
q 5 stack frame
p str
int main(void) {
int i; str 5 foo
i = 5; stack frame
printf("Before call: i is %d\n", i); x 5
foo(i); // call to function foo
printf("After call: i is %d\n", i); 5 main
return 0; stack frame
i 5
}
Functions: Pass-by-Value Convention
35
(12/20)
Before call: i is 5
In foo, x is 5
#include <stdio.h>

void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
}

int main(void) {
int i; foo
i = 5; stack frame
printf("Before call: i is %d\n", i); x 10
foo(i); // call to function foo
printf("After call: i is %d\n", i); 5 main
return 0; stack frame
i 5
}
Functions: Pass-by-Value Convention
36
(13/20)
Before call: i is 5
In foo, x is 5
#include <stdio.h> In foo, x is now 10

void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
} var1 var2 printf
stack frame
p str q 10
int main(void) {
int i; str 10 foo
i = 5; stack frame
printf("Before call: i is %d\n", i); x 10
foo(i); // call to function foo
printf("After call: i is %d\n", i); 5 main
return 0; stack frame
i 5
}
Functions: Pass-by-Value Convention
37
(14/20)
Before call: i is 5
In foo, x is 5
#include <stdio.h> In foo, x is now 10

void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
}

int main(void) {
int i; foo
i = 5; stack frame
printf("Before call: i is %d\n", i); x 10
foo(i); // call to function foo
printf("After call: i is %d\n", i); 5 main
return 0; stack frame
i 5
}
Functions: Pass-by-Value Convention
38
(15/20)
Before call: i is 5
In foo, x is 5
#include <stdio.h> In foo, x is now 10

void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
}

int main(void) {
int i;
i = 5;
printf("Before call: i is %d\n", i);
foo(i); // call to function foo
printf("After call: i is %d\n", i); main
return 0; stack frame
i 5
}
Functions: Pass-by-Value Convention
39
(16/20)
Before call: i is 5
In foo, x is 5
#include <stdio.h> In foo, x is now 10
After call: i is 5
void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
}

int main(void) {
int i; printf
var1 var2
i = 5; stack frame
printf("Before call: i is %d\n", i); p str q 5
foo(i); // call to function foo
printf("After call: i is %d\n", i); str 5 main
return 0; stack frame
i 5
}
Functions: Pass-by-Value Convention
40
(17/20)
Before call: i is 5
In foo, x is 5
#include <stdio.h> In foo, x is now 10
After call: i is 5
void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
}

int main(void) {
int i;
i = 5;
printf("Before call: i is %d\n", i);
foo(i); // call to function foo
printf("After call: i is %d\n", i); 0 main
return 0; stack frame
i 5
}
Functions: Pass-by-Value Convention
41
(18/20)
Before call: i is 5
In foo, x is 5
#include <stdio.h> In foo, x is now 10
After call: i is 5
void foo(int x) {
Stack
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
}

int main(void) {
int i;
i = 5;
printf("Before call: i is %d\n", i);
foo(i); // call to function foo
printf("After call: i is %d\n", i);
return 0;
}
Functions: Pass-by-Value Convention
42
(19/20)
Before call: i is 5
In foo, x is 5
#include <stdio.h> In foo, x is now 10
After call: i is 5
void foo(int x) {
printf("In foo, x is %d\n", x);
x = 10; Main takeaway:
printf("In foo, x is now %d\n", x); Inter-function communication
}
uses pass-by-value semantics.
int main(void) { Using the stack, copy of
int i; argument i is passed to
i = 5;
printf("Before call: i is %d\n", i); function foo to initialize
foo(i); // call to function foo parameter x.
printf("After call: i is %d\n", i); Changes made to parameter
return 0;
} x do not affect argument i!!!
Functions: Pass-by-Value Convention
43
(20/20)
 Visualization of program
#include <stdio.h>

void foo(int x) {
printf("In foo, x is %d\n", x);
x = 10;
printf("In foo, x is now %d\n", x);
}

int main(void) {
int i;
i = 5;
printf("Before call: i is %d\n", i);
foo(i); // call to function foo
printf("After call: i is %d\n", i);
return 0;
}
Pass-by-Value Convention: Example
44

 Specify the ordered sequence of function calls


made by this program. Write - in order - the
functions that are called (including functions
main and printf) and the arguments
associated with each of these calls.
Pass-by-Value Convention:
45
Example [Answers]
Function called Argument 1 Argument 2
main void -
printf "main's local variable x is originally: %d\n" 1
boo 2 -
printf "boo's local variable x is originally: %d\n" 2
coo 4 -
printf "coo's local variable x is originally: %d\n" 4
doo 7 -
printf "doo's local variable x is originally: %d\n" 7
printf "doo's local variable x is now : %d\n" 11
printf "coo's local variable x is now : %d\n" 15
printf "boo's local variable x is now : %d\n" 18
printf "main's local variable x is now : %d\n" 20
Summary
46

 Function is encapsulation of algorithm


 Function prototype/declaration
 Function definition
 Function call operator
 Function arguments and parameters
 Call by value semantics
 Role of stack in implementation of call by value
semantics
 Tracing functions and identifying arguments
HIGH-LEVEL PROGRAMMING I
Increment/Decrement
Operators by Prasanna Ghali
Increment and Decrement
2
Operators (1/2)
 Variables are incremented to keep track of how
many times certain things have happened
int counter;
// some code here
counter = counter + 1;
// some more code here

 C/C++ provide compound assignment operator to


condense incrementing int counter;
// some code here
counter += 1;
// some more code here
}
Increment and Decrement
3
Operators (2/2)
 To further expedite execution of these assignment
statements, C/C++ provide:
 incrementoperator ++ to increase variable’s value by 1
 decrement operator -- to decrease variable’s value by 1

 Increment and decrement operators each have two


forms: prefix and postfix
Postfix-increment variable++
Postfix-decrement variable--

Prefix-increment ++variable
Prefix-decrement --variable
lvalue Operands
4

 Operand expr for increment and decrement


operators must be an lvalue (that is, it must be
a variable)
 Result of all four expressions is rvalue

 Suppose x is a variable (of any scalar type)

Prefix Increment Prefix Decrement Postfix Increment Postfix Decrement


++10 --x x++ 10--
k = ++x k = --x k = x++ k = x--
++x = 10 --x = 10 x++ = 10 x-- = 10
Postfix Increment and Decrement
5
Operators (1/2)
 Meaning of postfix operators variable++
and variable--:
 Bump up or down variable after using its original
value in surrounding expression
 Suppose we’ve variable x of type int
Contents of Value of Contents of x after
Expression
x before expression sequence point
10 x++ 10 11
10 x-- 10 9
Postfix Increment and Decrement
6
Operators (2/2)

Contents of Value of Contents of x after


Expression
x before expression sequence point
10 x++ 10 11
10 x-- 10 9

 If i and j are int variables, statement i=j--;


can be equivalently rewritten in any of 3 ways:
i = j; i = j; i = j;
j = j - 1; j--; --j;
Compiler’s Perspective: Postfix
7
Operators
 From compiler’s perspective, expression
variable++ means
 Get location of variable in memory
 Load contents at this location into CPU register, say r0

 Use value in r0 register in expression


 Increment value in register r0

 Store incremented value in r0 to location of variable


in memory
 Side effect of storing incremented value in variable
will occur at next sequence point
Prefix Increment and Decrement
8
Operators (1/2)
 Meaning of prefix operators ++variable
and --variable:
 Bump up or down variable before using its value
in surrounding expression
 Suppose we’ve variable x of type int
Contents of Contents of
Expression Value of expression
x before x after
10 ++x 11 11
10 --x 9 9
Prefix Increment and Decrement
9
Operators (2/2)
Contents of Contents of
Expression Value of expression
x before x after
10 ++x 11 11
10 --x 9 9

 If i and j are int variables, statement i=--j;


can be equivalently rewritten in any of 3 ways:
j = j - 1; j--; --j;
i = j; i = j; i = j;
Prefix Increment and Decrement
10
Operators (2/2)
 From compiler’s perspective, expression
++variable means
 Get location of variable in memory
 Load contents at this location into a CPU register

 Increment contents of this CPU register

 Store incremented value in register to location of


variable in memory
 Use incremented value in register in expression
Equivalence
11

 Following statements have same effect:

Compound Prefix Postfix


Assignment
Assignment Increment Increment
x = x + 1; x += 1; ++x; x++;

Compound Prefix Postfix


Assignment
Assignment Decrement Decrement
x = x - 1; x -= 1; --x; x--;
Precedence and Associativity
12

Operator Meaning Associativity

() parentheses or grouping L-R


++ -- Postfix increment/decrement L-R
++ -- Prefix increment/decrement R-L
+ - unary plus, unary minus R-L
* / % multiplication, division, remainder L-R
precedence order
high to low

+ - addition, subtraction L-R


< <= > >= relational L-R
== != Equivalence L-R
&& logical AND L-R
|| logical OR L-R
= assignment R-L
, comma L-R
Increment and Decrement
13
Operators: Example 0 (1/2)
 Assume all variables are of type int with a
initialized to value 5 before each statement
 Provide values after statement is executed …

Statement Value of a Value of b Value of c


c = a++; -
c = ++a; -
c = b = a++;
c = b = ++a;
Increment and Decrement
14
Operators: Example 0 (2/2)
 Assume all variables are of type int with a
initialized to value 5 before each statement
 Provide values after statement is executed …

Statement Value of a Value of b Value of c


c = a++; 6 - 5
c = ++a; 6 - 6
c = b = a++; 6 5 5
c = b = ++a; 6 6 6
Increment and Decrement
15
Operators: Example 1 (1/2)
 Assume all variables are of type int with a
and b initialized to values 5 and 3 before
each statement
 Provide values after statement is executed …

Statement Value of a Value of b Value of c


c = a++ + b++;
c = ++a + b++;
c = a++ + ++b;
c = ++a + ++b;
Increment and Decrement
16
Operators: Example 1 (2/2)
 Assume all variables are of type int with a
and b initialized to values 5 and 3 before
each statement
 Provide values after statement is executed …

Statement Value of a Value of b Value of c


c = a++ + b++; 6 4 8
c = ++a + b++; 6 4 9
c = a++ + ++b; 6 4 9
c = ++a + ++b; 6 4 10
Increment and Decrement
17
Operators: Example 2 (1/2)
 Write comma separated list of tokens extracted by
compiler (indicate whether expression is legal or not)
 Recallfrom earlier part of course that a token is group of
characters that cannot be split up without changing their
meaning
Expression List of Tokens Legal?
j+++k
j++++k
j+++++k
j+++ ++k
Increment and Decrement
18
Operators: Example 2 (2/2)
 Write comma separated list of tokens extracted by
compiler (indicate whether expression is legal or not)
 Recall from earliest part of course that a token is group
of characters that cannot be split up without changing their
meaning

Expression List of Tokens Legal


j+++k j, ++, +, k 
j++++k j, ++, ++, k ×
j+++++k j, ++, ++, +, k ×
j+++ ++k j, ++, +, ++, k 
Increment and Decrement
19
Operators: Example 3 (1/2)
 Which of following expressions are legal?
 Assume variables j and k are of type int

and are initialized with values 1 and 2


If legal, value of
Expression Legal or not?
expression
j+++k
j++++k
j+++++k
j+++ ++k
Increment and Decrement
20
Operators: Example 3 (2/2)
 Which of following expressions are legal?
 Assume variables j and k are of type int

and are initialized with values 1 and 2


If legal, value of
Expression Legal or not?
expression
j+++k  3
j++++k × -
j+++++k × -
j+++ ++k  4
Increment and Decrement
21
Operators: Example 4 (1/2)
 Are following expressions evaluated unambiguously?
 Assume variable j is of type int and is initialized
with value 1

If unambiguous,
Expression Unambiguous?
value of expression
j++*j++
++j*++j
++j*j++
j++*++j
Increment and Decrement
22
Operators: Example 4 (2/2)
 Are following expressions evaluated unambiguously?
 Assume variable j is of type int and is initialized
with value 1
If unambiguous,
Expression Unambiguous? value of
expression
j++*j++ No Unspecified behavior

++j*++j No Unspecified behavior

++j*j++ No Unspecified behavior

j++*++j No Unspecified behavior


Increment and Decrement
23
Operators: Example 5
 What is printed to #include <stdio.h>
#include <stdbool.h>
standard output by
int main(void) {
code fragment? int i = 1, j = 1, k = 1;
bool flag = ++i || ++j && ++k;
if (flag == true) {
printf("flag is true\n");
}
printf("%d %d %d\n", i, j, k);

i = 7; j = 8; k = 9;
flag = i - 7 && j++ < k;
if (flag == false) {
printf("flag is false\n");
}
printf("%d %d %d\n", i, j, k);
}
HIGH-LEVEL PROGRAMMING I
Jump Statements by Prasanna Ghali
Jump Statements
2

 Jump statements alter sequential flow of


control of C/C++ programs
 4 jump statements:

 return statement
 break statement

 continue statement

 goto statement [not covered in this course]


return Statement (1/2)
3

 General format:

return expressionoptional;
return Statement (2/2)
4

 1st purpose is to provide return value for a


function
 For example, last statement of main function returns
int value: return 1;
 To return nothing because function returns void, simply
say: return;
 2nd purpose is to unilaterally jump out of function
if mission is accomplished or if it is determined
that mission cannot be accomplished because of
missing information
break Statement
5

 Typically used in 2 scenarios:


 To skip remainder of a switch structure
 To exit early from an iteration structure

 After break statement executes, program


execution jumps to first statement after
switch or iteration structure
break Statement: Example 1
6

switch (year) {
case 1:
int year = 1; printf("Freshman\n");
if (1 == year) { break;
printf("Freshman\n"); case 2:
} else if (2 == year) { printf("Sophomore\n");
printf("Sophomore\n"); break;
} else if (3 == year) { case 3:
printf("Junior\n"); printf("Junior\n");
} else if (4 == year) { break;
printf("Senior\n"); case 4:
} else { printf("Senior\n");
printf("Who are you?\n"); break;
} default:
printf("Who are you?\n");
}
break Statement:
7
Flow of Control in Loop

for (/* expressions */) {


// statements
break;
// more statements
}
// break jumps here
// even more statements
break Statement: Example 2 (1/2)
8

 Find sum of numbers entered from standard input


until first negative number (without break)
#include <stdbool.h>
int sum = 0, num;
bool isNegative = false;
while (!isNegative && scanf("%d", &num)) {
if (num < 0) {
isNegative = true;
} else {
sum += num;
}
}
printf("Sum: %d\n", sum);
break Statement: Example 2 (2/2)
9

 Advantage of break statement is that it


eliminates flag variables
int sum = 0, num;
while (1 == scanf(" %d", &num)) {
if (num < 0) {
break;
}
sum += num;
}
printf("Sum: %d\n", sum);
break Statement: Example 3
10

 Useful for escaping from infinite loops


int i = 1; int i = 1;
for (;;) { while (1) {
printf("%d ", i); printf("%d ", i);
i += 1; i += 1;
if (i > 10) { if (i > 10) {
break; break;
} }
} }
continue Statement (1/3)
11

 Used in while, do…while, for structures to


skip remaining statements in loop and proceed
with next iteration of loop
continue Statement (2/3)
12

 In while and do…while structures, loop


condition test is evaluated immediately
after continue statement
initial statement 1
do
while (loop condition) {
statement 1
statement 1
...
...
continue;
continue;
...
...
statement n
statement n
while (loop condition);
}
continue Statement (3/3)
13

 In for statement, execution jumps to update


expression after continue statement and
then loop condition test

for (initial expression; loop condition; update expression)


{
statement 1
...
continue;
...
statement n
}
continue Statement: Flow of
14
Control in Loop

for (/* expressions */) {


// statements
continue;
// more statements
// continue jumps here
}
// even more statements
continue Statement: Example
15

 Find sum of numbers entered from standard


input excluding negative numbers
int sum = 0, num;
while (1 == scanf("%d", &num)) {
if (num < 0) {
continue;
}
sum += num;
}
printf("Sum: %d\n", sum);
HIGH-LEVEL PROGRAMMING I
Order of operand
evaluation by Prasanna Ghali
References
2

 C’s side effects are explained here


 C’s sequence points are explained here

 Order of operand evaluation are explained


here
What are Side Effects?
3

 Side effect is change in state of program’s


execution state and is achieved by modifying
C/C++ entities with memory storage
 Following side effect operators modify
associated operand
 Assignment,
compound assignment, prefix increment
and decrement, and postfix increment and
decrement
 c = a++ * --b; // three changes
Side Effects: Examples (1/2)
4

Expression Side effect? (Y or N)


++n
-x
!b
m = n
m += n
m + n
m - n
printf("%d %d", m, n)
Side Effects: Examples (2/2)
5

Expression Side effect (Y or N)


++n yes
-x no
!b no
m = n yes
m += n yes
m + n no
m - n no
yes (stdout is
printf("%d %d", m, n)
modified)
Sequence Points (1/5)
6

 Evaluation of expression may produce side


effects
 What are values of a and b after evaluation
of following statement? int a = 10, b;
b = a++ + ++a;
 Undefined behavior – a could be 11 or 12
and b could be 21 or 22
 Why does statement generate undefined
behavior?
Sequence Points (2/5)
7

 At specific points during execution, known as


sequence points, all side effects of previous
evaluations are complete, and no side effects
of subsequent evaluations have yet taken
place
 In simpler terms: sequence point is location in

program text where the previous dust has


settled (that is, all operations have been
executed) before new operations are executed
Sequence Points (3/5)
8

 We should be aware of following sequence points


 Between evaluations of 1st and 2nd operands for logical
AND, logical OR, and comma operators
 Between evaluations of 1st operand of ?: operator
and whichever of 2nd and 3rd operands is evaluated
 Controlling expression of if and switch statement

 Loop condition of while or do statement

 Each of 3 expressions of for statement


Sequence Points (4/5)
9

 What are values of a and b after evaluation of


following statement? int a = 10, b;
b = a++ + ++a;

 Undefined behavior – a could be 11 or 12 and b


could be 21 or 22
 Why? There are two problems:
 Increment/decrement operators can only guarantee
increment/decrement will be complete after next
sequence point
 Order of operand evaluation is unspecified – can’t
say whether a++ or ++a is evaluated first
Sequence Points (5/5)
10

 Another example of undefined behavior:


int a = 4, b;
// a modified twice between sequence points
b = a * a++; // dangerous code

 Depending on whether left or right operand of


operator * is evaluated first, b could have
value of either 16 or 20
 GCC will issue a warning with –Wall option:
warning: operation on 'a' may be undefined
Order of Evaluation
11

 Consider expressions that use multiple


operators and are composed of multiple
subexpressions
 x = foo() + boo()
r = w * x + y * z
 r = x++ + ++x
 x = coo(++x) + doo(x)
 In general, assume order of operand
evaluation is unspecified
Order of Evaluation: Example 1
12

 Undefined behavior void func(int x, int y);

void foo(int i) {
func(i++, i);
}

 Compliant code void func(int x, int y);

void foo(int i) {
func(i, i+1);
i++;
}
Order of Evaluation: Example 2
13

 Undefined behavior int i = 5;


i = i++;

 Subexpression i++ causes side effect while i is


also referenced elsewhere in same expression
 No way to know if reference will happen before or
after side effect
 Compliant code
int i = 5;
i = i + 1;
Order of Evaluation: Example 3
14

 What is printed to standard output?


 Order of operand evaluation is unspecified!!!
int boo(void) {
printf("I'm boo\n"); Could be either:
return 10;
} I'm boo
I'm foo
int foo(void) {
printf("I'm foo\n"); 10 and 20
return 20;
} OR

int main(void) { I'm foo


printf("%d and %d\n", boo(), foo()); I'm boo
return 0;
} 10 and 20
Order of Evaluation: Example 4
15

 Taking advantage of order of operand evaluation


 There’s special “short-circuiting” behavior for logical AND
(and also for logical OR) operator
 If left operand determines value and result for expression,
then right operand is not evaluated
/*
continue to read characters from standard input until
there are no more characters to be read or until a
newline is encountered
*/
while ((ch = getchar()) != EOF && ch != '\n') {
// some useful code here
}
Summary
16

 What is side effect?


 What is undefined behavior and when does it

arise?
 What is sequence point?

 What is order of operand evaluation mean?

 Which operators specify order of operand

evaluation
 How to write compliant code
HIGH-LEVEL PROGRAMMING I
switch Statement by Prasanna Ghali
switch Statement (1/5)
2

 C/C++ provide two


selection structures int year = 1;
if (1 == year) {
 When implemented with printf("Freshman\n");
either if or if...else } else if (2 == year) {
printf("Sophomore\n");
statement, usually requires } else if (3 == year) {
evaluation of logical printf("Junior\n");
expression } else if (4 == year) {
printf("Senior\n");
} else {
printf("Who are you?\n");
}
switch Statement (2/5)
3

 C/C++ provide two selection structures


 When implemented with if or if...else
statement, usually requires evaluation of logical
expression
 2nd type doesn’t require evaluation of logical
expression and is called switch structure
switch Statement (3/5)
4

switch (integral-expression) {
case integral-value-1: Referred to as label
statements-1
break; Value must be known at compile-
case integral-value-2: time i.e., expression must not
statements-2 contain variables
break;
... Causes program execution to
case integral-value-n: jump to statement after switch
statements-n statement
break;
default label corresponds to a
default:
value that doesn’t match any of
statements
the other labels
}
switch Statement (4/5)
5

int year = 1;
switch (year) {
case 1:
int year = 1; printf("Freshman\n");
if (1 == year) { break;
printf("Freshman\n"); case 2:
} else if (2 == year) { printf("Sophomore\n");
printf("Sophomore\n"); break;
} else if (3 == year) { case 3:
printf("Junior\n"); printf("Junior\n");
} else if (4 == year) { break;
printf("Senior\n"); case 4:
} else { printf("Senior\n");
printf("Who are you?\n"); break;
} default:
printf("Who are you?\n");
}
switch Statement (5/5)
6

 What is text printed to standard output?


int level = 5;
printf("Spell list: ");
switch (level) {
case 5:
printf("Firestorm");
case 4:
case 3:
printf("Fireball");
case 2:
case 1:
printf("Firebolt");
}

You might also like