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

01B LanguageSyntax Basics Types Variables Scopes Operators Statements Switch Enum Functions

The document provides an overview of the key topics to be covered in a programming workshop on C/C++ syntax, including: variable types and scope, conditional and loop statements, operators, functions, macros, and header files. The expected learning outcomes are to get a broad overview of C syntax and learn to program simple C programs using this syntax.

Uploaded by

moamin.shikha
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

01B LanguageSyntax Basics Types Variables Scopes Operators Statements Switch Enum Functions

The document provides an overview of the key topics to be covered in a programming workshop on C/C++ syntax, including: variable types and scope, conditional and loop statements, operators, functions, macros, and header files. The expected learning outcomes are to get a broad overview of C syntax and learn to program simple C programs using this syntax.

Uploaded by

moamin.shikha
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 114

A broad overview of

C and its syntax

Programming Workshop in C/C++ (67315)


Week 1B
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

0 Learn to program simple C programs using this syntax

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

0 Learn to program simple C programs using this syntax

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

const int x = 3; // initialization is ok


x = 5; // ERROR – cannot reassign a value
to a const type

 A const-qualified variable cannot be on the left


side of an assignment operator (qualified = ‫)מסוייג‬
 It can be initialized!
 const protects us from our worst “enemy”:
ourselves
8
Scope of variables and { … }

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

• Only declarations inside current or outer scopes are visible

• Declarations in inner scope hide declarations in outer scopes

• Outmost scope (global) has no brackets

• Keep in mind that a function is also a scope

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

C is a statically-typed language (unlike Python).


The compiler must know the type of each variable at compile-time

Variables of different types have different size,


internal representation, and API that uses them.
● size: the amount of memory they take on a specific computer architecture

● internal representation – the exact bit pattern

● API (interface): operators/functions that can use it for input/output

* Part of the above is defined by the C standard, while part of it is implementation dependent

15
Variable types – Python vs. C

Python – Dynamically typed language (types can change)


C - Statically typed language (types are fixed)

# Python Code // C Code


x = 4 # x is an integer int x = 4; // integer
x = ”I am a string!" x = "I am a
string!"; //Error!

More on the differences between Python and C:


16
https://www.geeksforgeeks.org/difference-between-c-and-python/
Types of variables in C

Scalar (primitive) types:

● Arithmetic data types

● Enumeration types (user-defined)

● Pointers

Aggregate types:

● Arrays

● Structs & Unions (user-defined)

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)

Floating-point types: Tradeoff: Memory vs.


● float range and precision
● double
● long double

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;

unsigned char uc = 'A';


signed char sc = 'D';
unsigned short us = 0;
unsigned int ui = 1;
unsigned long ul = 0x1FF; // hexadecimal (base 16)

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

int x = 75; implicitly cast


int to float
int y = 100; explicitly cast
float z = x / y; // = 0.0 x to float
float z = (float) x / y; // = 0.75
int z = (float) x / y; // = 0 float / int

== float
float to int: truncate
towards zero (10.310,
-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’

unsigned char y = x; // x and y have identical types


y = x + 3; // y  'A'+3=='D'

// p_byte is an alias for a pointer to a byte (week 2)


typedef byte* p_byte;

// byte10 is an alias for an array of 10 bytes (week 2)


typedef byte[10] byte10;

25
enum types: humean-
readable constants

26
Human-readable constants vs.
“magic numbers”
Which code snippet better conveys the logic of the code?

if (x==2) // “magic number” if (x==E_SPRING) // constant


{ {
printf("%s\n", printf("%s\n",
"It’s getting warmer!"); "It’s getting warmer!");
} }

Magic number: A unique value with unexplained meaning or multiple occurrences


which could/should be replaced with a named constant
 In this course, magic numbers other than 0, 1 must be replaced by human-readable

constants using enum, #define. Outside course, use common sense.

27
Human-readable constants are usually
preferred over “magic numbers”

• More readable code

• Code less error-prone

• implemented in C using enum (compiler)


or #define (pre-processor)

?Why are magic numbers bad? Or are they


https://en.wikipedia.org/wiki/Magic_number_(programming)

28
enum: a user-defined constant integral type
Declaration of enum type:

enum [ <tag> ]
{ <CONSTANT> [ = <integer> ],
<CONSTANT> [ = <integer> ], … };

Declaration of enum variable (“instantiation”):

enum <tag> <variable-name> [ = <CONSTANT> ];

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

enum Color {BLACK, RED, GREEN, YELLOW, BLUE, WHITE=7, GRAY};


enum Color color = BLUE; // initialized to 4
color = GRAY; // assigned 8

enum { SUNDAY=1, MONDAY, TUESDAY, …}; // tag is optional


int day = MONDAY; // initialized to 2

30
enum with typedef

typedef enum <tag>


{
<enumeration_list>
} <new type name>;

31
enum with typedef

typedef enum Seasons_tag enum identifier (tag)


{
E_WINTER,
E_SPRING,
E_SUMMER,
E_AUTUMN
} Season_type; new type name

enum Seasons_tag ca = E_WINTER; // ok even without typedef


Seasons_type s = E_SUMMER; // ok only with typedef

32
enum with typedef
one could use an identical tag and type name for convenience

typedef enum Seasons enum identifier (tag)

{
E_WINTER, // = 0 by default
E_SPRING, // = E_WINTER + 1
E_SUMMER, // = E_WINTER + 2
E_AUTUMN // = E_WINTER + 3
} Seasons; new type name

enum Seasons ca = E_WINTER; // ok even without typedef


Seasons s = E_SUMMER; // ok only with typedef

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);

y = (x > 0) ? 10 : 100; if (x > 0)


{
y = 10;
}
else
{
y = 100;
}

36
switch & enum

37
switch conditional statements
branch code by comparing a variable to a constant integer value

switch (n) // integer only (int, char, short, _Bool, etc.)


{
case 1:
// code executed if n = 1;
break;
case 2:
// code executed if n = 2;
break;
default:
// code executed if n doesn't match any case
}

38
Case expression is a constant integer

The expression must be an integral type whose value


can be evaluated in advance (“compile time”)

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.)

• duplicate case values are not allowed

• the default statement is optional and can be placed


anywhere. it will be still executed if no match is found

• the break statement is optional

• all statements following a matching case execute


until a break is reached

• 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:

printf("Choice other than 1, 2 and 3\n");


}
return 0;

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:

printf("Choice is 1\n"); break;


case 2:

printf("Choice is 2\n"); break;


case 3:

printf("Choice is 3\n"); break;


default:

printf("Choice other than 1, 2 and 3\n");


}
return 0;

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

// for( initial; test; update);


int i = 0; // declare outside to keep in scope
for (; i<10; i++); // we can skip 1st expression
printf ("%d\n", i);

10

50
for loop with “,”

// for( initial; test; update)


for (int i=0, j=0; i<10 && j<5; i++, j+=2)
{
printf ("%d %d\n", i, j);
}

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

The Programmer got stuck in the shower, why ?

Because the instructions on the shampoo bottle said


Lather, Rinse, Repeat

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

Operator Meaning Examples


+ addition int x = y + 3;

- 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

All assignment operators return the assigned value


 chaining
Operator Meaning Examples
= assignment int x = (y = 3); // y=3; x=3

+= -= *= /= Operation- int x = (y+=3); // y=y+3; x=y;


%= >>= assignment int x = (y-=5); // y=y-3; x=y;
<<= &= ^= (e.g., addition- int x = (y*=2); // y=y*2; x=y;

|= assignment)
++ (pre) Pre-increment int x = ++y; // y=y+1; x=y;
-- (pre)
++ (post) Post-increment int x = y++; // x=y; y=y+1;
-- (post)

59
Assignment returns the assigned value

int x = (y = 3); // (y = 3) returns 3


x = y = 3; // equivalent: evaluated right-to-left
if ( (x*=2) > 5) // true!
{
...
}

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

++x; x += 1; post-increment (doesn’t matter)

y = ++x; x += 1; Pre-increment: x is first


incremented and then assigned to y
y = x;
y = x++; y = x; Post-increment: x is assigned to y
and incremented afterwards
x += 1;

Code runner L1A.Q3


62
?Q: What’s the output
{
int x = 0;
{
int x = 5;
x++;
}
printf("x = %d\n", --x);
}

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
{ … }

while (1) // true (run forever)


{ … }

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;
}

assert(<condition>) terminates the program if !


<condition>. It is used for sanity checks during
development and is typically disabled in production mode
(we will learn about NDEBUG and assert later…)
https://www.geeksforgeeks.org/assertions-cc/
69
assert() – debugging with boolean
expressions
#include <assert.h>

int main()
{
const int x = 6;
assert (x!=3); // more readable
float c = 1.0f / (x-3);
return 0;
}

assert(<condition>) terminates the program if !


<condition>. It is used for sanity checks during
development and it is typically disabled in production mode
(we will learn about NDEBUG and assert later…)
https://www.geeksforgeeks.org/assertions-cc/
70
The _Bool keyword

• _Bool is an unsigned integer type that can store 0 and 1.


• Any other integer type (e.g. int) can be converted to _Bool
• Non-zero is converted to 1, zero remains 0

_Bool b1 = 19; // 1
_Bool b2 = 0; // 1

int i = -20;
_Bool b2 = i; // 1
_Bool b3 = !i; // 0

71
stdbool.h

Defines bool/false/true as _Bool/0/1, resp.


#include <stdbool.h>

bool loves_me = 5; // converted to 1


if (loves_me == true) // equiv. if (loves_me)
{
printf("loves me = %d\n", loves_me);
}
Code runner L2B

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)

A function declaration informs the compiler about a


function’s prototype: name, return type, and parameters

int power(int a, int b);


Return
name parameters
type

80
Functions - definition

The definition provides the actual function’s body: the


collection of statements that define what it does.

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)

void do_something( int a, int b )


{
// ...
return; Optional - return w/o a
value statement
}

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_c(int param);

void func_a() Declaration


{
}

void func_b()
{
func_c(7);
}

void func_c(int param)


{
Definition
}

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);

* Definition of the function is used for allocating memory


(“code memory”) for the function.
void func_c(int param)
{
}

85
Note on declaring functions without arguments

// a declaration for a function that takes an undetermined number/type of arguments


// (obsolescent = candidate for removal from standard C, do not use it)

void foo();

// a declaration for a function that takes no arguments


void foo(void);

86
Note on declaring functions without arguments

// a declaration for a function that takes an undetermined number/type of arguments


// (obsolescent = candidate for removal from standard C, do not use it)

void foo();

// a declaration for a function that takes no arguments


void foo(void);

// a definition for a function that takes no arguments

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:

We are using the


C99 standard -
avoid C11
headers

88
Practice – implement power
function

Code runner L1A.Q4

89
Preprocessor directives

90
The preprocessor and directives

#<directive> …

● A preprocessor is a special program that


processes code prior to its compilation

● Examples: #include, #define, #ifdef


● We will learn about it in detail later on

https://gcc.gnu.org/onlinedocs/cpp/Macros.html
91
#include directive
and header files

92
The #include pre-processor directive

• The #include directive tells the pre-processor


to copy-paste another file
• Including a file from the current folder:
#include "filename.h"
• Including a file from the compiler’s include paths:
#include <filename.h>

93
Header files

• We typically #include special files called


header files
• Header files typically contain shared API:
function signatures, enum declarations,
macros, etc.

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…

/** API: print hello to the standard output */


void say_hello();

#endif // 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

// implementation details (alternative 1)


void say_hello()
{
printf("Hello\n");
}

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

// implementation details (alternative 2)


void say_hello()
{
printf("Hello");
printf("\n");
}

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;
}

But how do we compile main.c together with hello.c?

99
Compiling multiple .c files (terminal)

> gcc –Wall -std=c99 main.c hello.c -o my_prog

> ./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

// header guard – we will learn #include “power.h”


about it later in the course…
#ifndef _POWER_H // computes integer power
#define _POWER_H int power(int base, int n)
{
/** int p = 1;
* Computes integer power for(int i=0; i<n; ++i)
* @return base to the power of n {
*/ p *= base;
int power(int base, int n); }
return p;
// end of header guard (later…) }
#endif // _POWER_H

10
Only .h file is needed when calling
the function from another source file
power.h file - interface main.c file – using power interface

// header guard – we will learn #include <stdio.h>


about it later in the course… #include “power.h”
#ifndef _POWER_H
#define _POWER_H int main()
{
/** for(int i = 0; i < 10; i++)
* Computes integer power {
* @return base to the power of n printf(”2 ^ %d = %d\n",
*/ i, power(2, i));
int power(int base, int n); }
return EXIT_SUCCESS; // = 0
// end of header guard }
#endif // _POWER_H

10
#define directive (macros)

10
#define, macros, and the preprocessor

#define <identifier> <macro>

• A macro is a code fragment that has been


given a name
• It is neither a variable or a function - just a
synonym
• Marcros are defined using the
#define preprocessor directive

https://gcc.gnu.org/onlinedocs/cpp/Macros.html
10
An object-like macro

• A simple identifier that will be replaced by a code-fragment

// object-like macro definition:


#define PI 3.141256f

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

• A simple identifier that will be replaced by a code-fragment

// object-like macro definition:


#define PI 3.141256f

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

• Parentheses after the macro identifier SQUARE

// object-like macro definition:


#define SQUARE(X) ((X)*(X)) // parentheses keep you safe

double square_difference(double x, double y)


{
// the preprocessor will substitute PI for 3.141256f
return SQUARE(x-y);
}

https://gcc.gnu.org/onlinedocs/cpp/Macros.html
10
A function-like macro

// object-like macro definition:


#define SQUARE(X) ((X)*(X)) // note the parentheses!

double square_difference(double x, double y)


{
// the preprocessor will substitute PI for 3.141256f
return SQUARE(x-y)((x-y)*(x-y));
}

https://gcc.gnu.org/onlinedocs/cpp/Macros.html
11
Caution – do not forget parentheses

// object-like macro definition:


#define SQUARE(X) X*X;

double square_difference(double x, double y)


{
// the preprocessor will substitute PI for 3.141256f
return SQUARE(x-y)x-y*x-y;
}

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

int x = 75; implicitly cast


int to float
int y = 100; explicitly cast
float z = x / y; // = 0.0 x to float
float z = (float) x / y; // = 0.75
int z = (float) x / y; // = 0 float / int

== float
float to int: truncate
towards zero (10.310,
-10.3-10)
11
‫?קוד לאודישן או קוד לפרודקשן‬

https://www.facebook.com/watch/?v=1090576338109340

Fibonacci in the L2 Code Runner!

11

You might also like