01B LanguageSyntax Basics Types Variables Scopes Operators Statements Switch Enum Functions
01B LanguageSyntax Basics Types Variables Scopes Operators Statements Switch Enum Functions
• Conditional statements
• Loop statements
• Operators
• Functions
• Macros
• Header files
2
Expected Learning Outcomes
0 Get a broad overview of C and its syntax
• Variable types and scope
• Conditional statements
• Loop statements
• Operators
• Functions
• Macros
• Header files
3
Variable declaration,
initialization & assignment
4
Variable declaration* + initialization
<type> <name> [= <init-value>];
int x = 5;
int y = 3, z = 2;
int j; // initial value undefined
Initialization of local variables is mandatory in
course! Arbitrary initial values (=garbage) can be
confusing to debug
* By default, in C variables are both declared (= name & type) and defined.(= associated with a memory address, later…)
5
Assignment (≠ initialization!)
<name> = new_value;
• You may initialize variables only once (when you declare them)
• You may assign new values to variables multiple times
• Both use the ‘=‘ symbol, but it takes a different meaning
int x = 5; // initialization
x = 10; // assignment
x = 12; // assignment
6
The const qualifier
7
const variables cannot be assigned a
new value
9
Variables
Where to declare?
1. Local: between curly braces {...} blocks – visible only in block
2. Global: outside all {...} blocks – visible everywhere
int x = 0; // global
int main()
{
int x = 1; //local hides global
{
int x = 2; //local hides outer scope
// x is 2
}
//x is 1 again
}
10
Scopes
• Code block defined with “{” and “}”
• Nesting is possible
11
Q: Scopes – what is the output?
int y = 9, x = 1; A) 9
{ B) 1
x = 7; C) 7
int x = y;
}
printf("%d", x);
A B C -
votehttp://hujicppbr.participoll.com/
at hujicppbr.participoll.com
12
Q: Scopes – what is the output?
int y = 5, x = 0; A) 5 0 0
{ B) 5 5 0
x = 3; C) 5 5 5
int x = y;
printf("%d ", x);
D) 5 5 3
{
int y = 0;
printf("%d ", x);
}
}
printf("%d", x);
A B C D 0
13 http://hujicppbr.participoll.com/
Variable types
14
Variable in C have fixed types
* Part of the above is defined by the C standard, while part of it is implementation dependent
15
Variable types – Python vs. C
● Pointers
Aggregate types:
● Arrays
17
Arithmetic data types
18
Arithmetic data types
Used in arithmetic operations: +, -, *, <,%, etc.
Integral types:
● char
● int
Why 6 integral and 3
● short floating-point types?
● long
● long long
● _Bool (Boolean)
19
Arithmetic data types - integers
char c='A', d=65; // a char is also a number!
short s = 0;
int i = 1;
long l = -9;
20
Arithmetic data types – real numbers
float x = 0.0;
double y = 1.0; // ~ double precision
x = x * 3.1234; // multiply by double
y = y * 1.2342f; // multiply by float
21
Type casting and truncation
22
Variables can be cast as other types
== float
float to int: truncate
towards zero (10.310,
-10.3-10)
23
typedef – define a new name
(alias for another type)
24
typedef <type-name> <new-name>;
// byte is an alias for unsigned char:
typedef unsigned char byte;
byte x = 'A';
x++; // x 'A'+1=='B’
25
enum types: humean-
readable constants
26
Human-readable constants vs.
“magic numbers”
Which code snippet better conveys the logic of the code?
27
Human-readable constants are usually
preferred over “magic numbers”
28
enum: a user-defined constant integral type
Declaration of enum type:
enum [ <tag> ]
{ <CONSTANT> [ = <integer> ],
<CONSTANT> [ = <integer> ], … };
29
enum usage
enum Seasons
{
E_WINTER, // = 0 by default
E_SPRING, // = E_WINTER + 1
E_SUMMER, // = E_WINTER + 2
E_AUTUMN, // = E_WINTER + 3
E_ALLSEASON = 100,
E_NOSEASON // = E_ALLSEASON + 1
};
enum Seasons seasons = E_SUMMER; // initialized to 2
seasons = 1000; // enum is just an int - technically this is legal
30
enum with typedef
31
enum with typedef
32
enum with typedef
one could use an identical tag and type name for convenience
{
E_WINTER, // = 0 by default
E_SPRING, // = E_WINTER + 1
E_SUMMER, // = E_WINTER + 2
E_AUTUMN // = E_WINTER + 3
} Seasons; new type name
33
Conditional Statements
34
Conditional statements - if
if (conditional-expression)
{
// ... (single statement or block)
}
else if (conditional-expression)
{
// ...
}
else
{
// ...
}
35
Conditional statements -
The trinary “? :” operator
(conditional expression) ? (expression 1) : (expression 2);
36
switch & enum
37
switch conditional statements
branch code by comparing a variable to a constant integer value
38
Case expression is a constant integer
int a = 1, b = 2;
const int c = 3;
…
case (1+2): // OK (can be evaluated in advance)
case (a+b): // invalid (known only at run time)
case (c): // invalid (const means read-only, not a real constant!)
case (3.14159): // invalid (not integral type)
case ‘A’: // OK (a char is an integral type!)
39
switch statement (cont.)
• nesting is allowed
40
enum and switch go hand in hand
int main()
{
typedef enum Color {RED,GREEN} Color;
enum Color my_color;
// scanf() = read characters from standard input and convert to specified format
// “%d” = read an integer
// Don’t worry about ‘&’ but if you can’t wait for next week, it passes the memory address of my_color to scanf()
scanf("%d", &my_color);
switch (my_color)
{
case RED:
printf("Your favorite color is red\n");
break;
case GREEN:
printf("green\n");
break;
default:
}
• printf("Unknown color\n");
the expression has to be constant value:
return 0;
}
41
Code runner – L1A.Q2
42
What is printed?
#include <stdio.h>
A. Choice is 2
Choice is 3
int main()
Choice other than 1, 2 and 3
{ B. Choice is 2
int x = 2; C. Choice is 2
switch (x) Choice other than 1, 2 and 3
{
case 1:
printf("Choice is 1\n");
case 2:
printf("Choice is 2\n");
case 3:
printf("Choice is 3\n");
default:
A B C 0
43
Never forget to break
#include <stdio.h>
A. Choice is 2
Choice is 3
int main()
Choice other than 1, 2 and 3
{ B. Choice is 2
int x = 2; C. Choice is 2
switch (x) Choice other than 1, 2 and 3
{
case 1:
A B C 0
44
A hidden dad joke
A programmer goes to the grocery store and her spouse asks:
- ”Please buy a gallon of milk, and if there are
eggs, buy a dozen."
So she follows through, and drive back to his house. Upon
arrival, her husband angrily asks her:
- "Why did you get 13 gallons of milk?"
The programmer says:
- "There were eggs!"
45
Loop Statements
46
for loop
for (initialization expression ;
test condition ;
update expression)
{
// for loop body
}
47
for loop
// for( initial ; test ; update )
for (int i = 0; i < 5; i++)
{
printf ("%d\n", i);
}
0
1
2
3
4
48
one-line for loop without curly braces
// for( initial ; test ; update )
for (int i = 0; i < 5; i++)
printf ("%d\n", i);
// not in course!
0
1
2
3
4
49
empty for loop
10
50
for loop with “,”
0 0
1 2
2 4
51
while / do-while loops
while (condition) do
{ {
// ... // ...
} } while (condition);
52
no-braces while / do-while loops
while (condition)
...; // not in course
53
A hidden dad joke
while (shampoo)
{
Lather;
Rinse;
Repeat;
}
54
Operators
55
Operator Types in C
Unary:
• Increment/decrement (assignment): ++ --
• Pointer, dereference, address: * &
• Size: sizeof()
Binary:
• Arithmetic: + - * / %
• Assignment: = += -= *= /= %= <<= >>= &= ^= |=
• Relational: < <= > >= == !=
• Logical: && || !
• Bitwise: & | ^ << >> ~
• Indexing/fields: () [] . ->
Ternary:
• conditional: ?:
56
Operator precedence & associativity
57
Arithmetic operators
• The order of evaluation (prededence) is as in algebraic expressions:
• brackets first, followed by * and /, followed by +/-
• from left to right
- subtraction int x = y - 3;
* multiplication float z = x * y;
/ division float x = 3 / 2; // = 1
float y = 3.0 / 2; // = 1.5
int z = 3.0 / 2; // = 1
% remainder int x = 3 % 2;
58
Assignment operators
59
Assignment returns the assigned value
60
Assignment is NOT Initialization
• Initialization happens during variable declaration/definition:
int x = 5;
• Assignment happens after the variable has already been
declared/defined (never on the declaration statement):
x = 3;
x *= 5;
• Const variables can be initialized but they cannot be assigned:
const int y = 5; //OK
y = 10; // ERROR
61
Pre- and post- increment/decrement operators
differ only in their returned values
++<var>, <var>++, --<var> and <var>-- act as shortcuts:
Operator Equivalent to.. Operation name
x++; x += 1; Pre-increment
A. x = 0
B. x = -1
C. x = 5
D. x = 6
A B C D 0
63
Boolean expressions,
assert & Boolean types
64
A boolean expression in C is just an
integer (0 = false; non-zero = true)
if (0) // false
{ … }
if (-1974) // true
{ … }
65
Relational and logical operators
return an int (0 = false; 1 = true)
int i=(19 == 74); // 0
int j=(19 == 19); // 1
int k=(13 < 19); // 1
int l=(i && k); // i and k 0
int m=(i || k); // i or k 1
int n=(!5); // not 5 0
66
Q: What’s the output? (debug with Clion!)
int x = 5; A. 5 4
while (1) B. 5 4 3
{ C. 4 3
printf ("%d\n", x--); D. Run forever
if (!(x-3)) What does x-- return?
When is !(x-3) true?
{
break;
}
}
A B C D 0
http://hujicppbr.participoll.com/
67
Q: What’s the output? (debug with Clion!)
int x = 5; A. 5 4
while (1) B. 5 4 3
{ C. 4 3
printf ("%d\n", x--); D. Run forever
if (!(x-3)) What does --x return?
When is !(x-3) true? -
{
break;
}
}
A B C D 0
http://hujicppbr.participoll.com/
68
assert() – debugging using boolean
expressions
#include <assert.h>
int main()
{
const int x = 6;
assert (!(x-3)); // terminate if x==3 zero-division
float c = 1.0f / (x-3);
return 0;
}
int main()
{
const int x = 6;
assert (x!=3); // more readable
float c = 1.0f / (x-3);
return 0;
}
_Bool b1 = 19; // 1
_Bool b2 = 0; // 1
int i = -20;
_Bool b2 = i; // 1
_Bool b3 = !i; // 0
71
stdbool.h
72
stdbool.h
#include <stdbool.h>
int main ()
{
bool loves_me = false;
while (true)
{
loves_me = !loves_me;
printf (loves_me ?
"loves me! \n" :
"loves me not! \n");
}
}
73
stdbool.h – careful!
#include <stdbool.h>
…
int loves_me = 5;
if (loves_me == true) // Won’t work! Why?
{
printf ("loves me = %d\n",
loves_me);
}
74
Solution 1: do not compare int to true
#include <stdbool.h>
…
int loves_me = 5;
if (loves_me==true) // ok now
{
printf ("loves me = %d\n",
loves_me);
}
75
Solution 2: store Boolean expressin in bool
#include <stdbool.h>
…
bool loves_me = 5; // 1
if (loves_me == true) // also ok
{
printf ("loves me = %d\n",
loves_me);
}
76
Short circuiting in C
• Boolean expression are evaluated from left to right
• Evaluation stops when the result is known
bool a = false;
bool b = true;
if (a && b) … // b is never evaluated
if (!a || b) … // b is never evaluated
77
Short circuiting in C - Usage
• Evaluation stops after (b != 0)
• Division-by-zero prevented
int a = 10, b = 0;
if ((b != 0) && (a/b > 2))
{
… // equivalent to:
if (b != 0)
} {
if (a/b > 2)
{
…
}
}
78
Functions
79
Functions – declaration (API; optional)
80
Functions - definition
int power( int a, int b ) If the function was not declared earlier –
the definition also serves as a declaration
{
int p = 1; Body statements
// …
// …
return statement
return x;
} end of function scope
81
Procedures
Functions that perform a task but return nothing (=void)
82
Function declaration order
//ok //ok
void func_a() void func_a() In C99, a function is
{ { only aware of earlier
... ... function declarations
} }
(earlier = above it).
void func_b() // error in C99
{ void func_b()
func_a(); {
} func_c(); func_c() was not declared yet.
}
void func_c()
{ void func_c()
func_b(); {
func_a(); func_b();
func_b(); }
}
83
Forward Declaration
Amendment to “Rule 1” : use forward declarations
void func_b()
{
func_c(7);
}
84
Summary:
Declaration “;” vs. Definition “{}”
* Declaration of a function provides the compiler the name
of the function, the number and type of arguments it takes
and its return type.
void func_c(int param);
85
Note on declaring functions without arguments
void foo();
86
Note on declaring functions without arguments
void foo();
void foo()
}
// or
“An empty list in a function declarator that is part of a definition
void foo(void) of that function specifies that the function has no parameters.
The empty list in a function declarator that is not part of a
{ definition of that function specifies that no information about the
number or types of the parameters is supplied.” (from the C99
} standad)
87
C standard library built in
functions
https://en.cppreference.com/w/c/header
Note:
88
Practice – implement power
function
89
Preprocessor directives
90
The preprocessor and directives
#<directive> …
https://gcc.gnu.org/onlinedocs/cpp/Macros.html
91
#include directive
and header files
92
The #include pre-processor directive
93
Header files
94
Header files allow us to separate the API
(interface) from the implementation details
API: hello.h
#ifndef _HELLO_H // header guard – ignore for now…
#define _HELLO_H // header guard – ignore for now…
95
Header files allow us to separate the API
(interface) from the implementation details
Implementation: hello.c
#include "hello.h" // copy-paste API from hello.h
#include <stdio.h> // copy-paste API for I/O
96
Header files allow us to separate the API
(interface) from the implementation details
Implementation: hello.c
#include "hello.h" // copy-paste API from hello.h
#include <stdio.h> // copy-paste API for I/O
97
Header files allow us to separate the API
(interface) from the implementation details
Usage: main.c
#include "hello.h" // copy-paste hello.h
Only the .h file with the function declaration is needed
int main()
{
say_hello();
return 0;
}
98
Header files allow us to separate the API
(interface) from the implementation details
Usage: main.c
#include "hello.h" // copy-paste hello.h
#include <stdlib.h> // copy-paste definition of EXIT_SUCCESS
int main()
{
say_hello();
return EXIT_SUCCESS;
}
99
Compiling multiple .c files (terminal)
> ./my_prog
hello
10
Compiling multiple .c files (CLion)
10
A good practice:
Declare in .h file, define in .c file
power.h file – API (interface) power.c file - implementation
10
Only .h file is needed when calling
the function from another source file
power.h file - interface main.c file – using power interface
10
#define directive (macros)
10
#define, macros, and the preprocessor
https://gcc.gnu.org/onlinedocs/cpp/Macros.html
10
An object-like macro
double circumference(double r)
{
// the preprocessor substitutes PI for 3.141256f
return 2 * PI * r;
}
https://gcc.gnu.org/onlinedocs/cpp/Macros.html
10
An object-like macro
double circumference(double r)
{
// the preprocessor substitutes PI for 3.141256f
return 2 * PI3.141256f * r;
}
https://gcc.gnu.org/onlinedocs/cpp/Macros.html
10
That’s how stdbool.h defines
bool/false/true
#define Bool_ bool
#define false 0
#define true 1
…
while (true)
{
}
10
A function-like macro
https://gcc.gnu.org/onlinedocs/cpp/Macros.html
10
A function-like macro
https://gcc.gnu.org/onlinedocs/cpp/Macros.html
11
Caution – do not forget parentheses
https://gcc.gnu.org/onlinedocs/cpp/Macros.html
11
#define multiple lines using ”\”
Multi-line:
All preprocessor directives affect one line (not an entire C
statement). To insert a line-break, use “\”:
BAD:
#define x (5 +
5)
GOOD:
#define x (5 + \
5)
// x == 10 !
11
Variables can be cast as other types
== float
float to int: truncate
towards zero (10.310,
-10.3-10)
11
?קוד לאודישן או קוד לפרודקשן
https://www.facebook.com/watch/?v=1090576338109340
11