CSC447
Concepts of Programming Languages
C: Statements versus Expressions
Instructor: James Riely
Is this C?
| int f (int x) { |
| int y; |
| if (x) y=1; else y=2; |
| return y; |
| } |
| int main() { printf ("%d\n", f(5)); return 0; } |
Is this C?
| int f (int x) { |
| int y; |
| y = if (x) 1 else 2; |
| return y; |
| } |
| int main() { printf ("%d\n", f(5)); return 0; } |
Is this C?
| int f (int x) { |
| int y; |
| y = x ? 1 : 2; |
| return y; |
| } |
| int main() { printf ("%d\n", f(5)); return 0; } |
Is this C?
| int f (int x) { |
| int w = x; |
| int y; |
| y = {int z=0; while (w>0) {w = w-1; z = z+1;} z} |
| return y; |
| } |
| int main() { printf ("%d\n", f(5)); return 0; } |
It can be written in Scala
| def f (x:Int):Int = { |
| var w = x; |
| var y:Int = 0; |
| y = {var z=0; while w>0 do {w = w-1; z = z+1}; z} |
| return y; |
| } |
| def main() = println (f(5)) |
Statements and Expressions
-
Assembly language consists of statements
-
Expressions were added later
-
Roughly:
-
Statements: should change memory
-
Expressions: should not
Pure / Side Effecting
-
A mathematical function takes arguments and gives results
-
An expression is pure if that's all it does
-
Anything else us a side effect
-
Assignment to a variable
-
Change of control (goto)
-
I/O (console, network)
-
etc.
Expressions
-
Literals (boolean, character, integer, string)
-
Operators (arithmetic, bitwise, logical)
-
Function calls
f (1 + (2 * strlen ("hello")))
Statements
-
Return statements
-
Selection statements (if-then-else; switch-case)
-
Iteration statements (while; do-while; for)
| int count = 0; |
| while (1) { |
| int ch = getchar (); |
| switch (ch) { |
| case -1: return count; |
| case 'a': count = count + 1; |
| default: continue; |
| } |
| } |
Expression statements (including assignment)
Side-Effecting Expressions
x++
x += 2
x = (y = 5)
x -= (y += 5)
Side-Effecting Expressions
| int global = 0; |
| |
| int post_inc () { |
| return global++; |
| } |
| |
| int main () { |
| printf ("%d\n", post_inc () + post_inc ()); |
| } |
C'S Comma Operator
-
(e1, e2, ..., en)
-
e1
... en-1
executed for side effect
-
Result is the value of
en
-
Sequential execution of expressions!
-
An example:
| string s; |
| while(read_string(s), s.len() > 5) { |
| |
| } |
Sequencing
| int main () { |
| int x = 5; |
| x *= 2; |
| printf ("%d\n", x); |
| } |
| int main () { |
| int x = 5; |
| printf ("%d\n", (x *= 2, x)); |
| } |
C Expressions
-
Sequencing:
e1, e2
-
Conditional:
e1 ? e2 : e3
-
Variable declarations?
-
Loops?
CSC447 Concepts of Programming Languages C: Statements versus Expressions Instructor: James Riely