Reading & exercises¶
(3-4h) Study Chapter 5 including exercise 5.7 p.281
2. Modularizing programs in C
C standard library
Meaning of defining, calling functions, and returning from functions
3. Math library functions
ceil,floor,sqrt,cbrt,fabs(float abs),pow,fmod,sin, ...
4. Functions
5. Function Definitions
Example:
squareSyntax
returnvsreturn value
vs function header: the first line of a function definition
argument coercion or type promotion
conversion in mixed-type expressions
Function prototype notes:
If there’s no function prototype for a function, the compiler forms one from the first occurrence of the function—either the function definition or a call to the function. This typically leads to warnings or errors, depending on the compiler.
Part of this information is dated, this was true before the C standard C99. Newer C standard do not create a prototype for you, if you use a function without declaring it first.
7. Function call stack and stack frames
function call order (Function-call stack in action)
8. Headers
e.g.,
string.h,time.h
9. Passing arguments by value and by reference
10. Random-number generation
randfromstdlib.hrange 0 to
RAND_MAXscaling using
%%sconversion specifier for strings. (was introduced in section 2.7 first, and then 3.8)
11. Case study: Rock ✊🪨, paper ✋📄, scissors ✌️✂️
enum {A, B, C} mytype_tenumerated typeused
char *: it returns a string, e.g.,char *f() { return "hello"; }
defines storage duration (e.g.,
static), scope (visibility), and linkage (not discussed here)auto(implicit for function variables) vsstatic[1]staticvsextern: block or compilation unit scope vs global scopeglobal variables and function names are extern as default
we should try to avoid global variables
13. Scope rules
function scope (inside a function)
file scope (defined outside any function)
block scope (
{})function-prototype scope (variable names)
14. Recursion
15. Example using recursion: Fibonacci series
recursion has function calling overhead, so choose iteration if you can.
good software engineering vs high performance
17. Security: Secure random-number generation
industrial security requires true random number generation. Do not use
randfor this purpose!
staticis relevant for interrupts in microcontroller programming, where we may want a variable in the interrupt handler to survive also after the function’s return.