Functions, Variables and Scope
In questa pagina 4
The deck is titled "functions declaration and definition" and also announces scope rules, but its slides contain no dedicated section on scope or storage classes: only the notes on declarations below. Do not rely on these notes for scope rules.
Variables
- In C all variables must be declared before use, usually at the beginning of the function before executable statements. A declaration is a type plus a list of names:
int fahr, celsius;. - Variables hold values used during the computation; assignment statements set initial values:
fahr = 0;. - Declaring the counter in the
forheader is used by the slides:for (int i = 1; i <= n; ++i). - Names are case sensitive. Symbolic constants with
#definereplace magic numbers (Control StructuresBasic syntax rules and the control structures of C: if/else, switch, the ternary operator, goto, symbolic constants and the while, for and do-while loops with break and continue.Control Structures →). - Types and conversions: Primitive Data Types and ExpressionsC data types (basic, derived, enum, struct and union, void, bool), arithmetic, comparison, logical and bitwise operators, type conversions and the rules for evaluating expressions.Primitive Data Types and Expressions →.
Functions
A function encapsulates a computation that can be used without caring about its implementation: it is enough to know what it does, not how. It can be called repeatedly. Functions are also how problems are decomposed into sub-problems (Introduction to C and the Development WorkflowWhat a computer and a program are, how algorithms are specified with preconditions and postconditions, why C is a compiled language, and the structure of a first C program.Introduction to C and the Development Workflow →).
Definition
return-type function-name(parameter declarations, if any)
{
declarations
statements
}Example from the slides: C has no exponentiation operator, so write power(m, n) raising an integer to a non-negative power.
#include <stdio.h>
int power(int base, int n); /* prototype */
main() /* test power function */
{
int i;
for (i = 0; i < 10; ++i)
printf("%d %d %d\n", i, power(2,i), power(-3,i));
return 0;
}
/* power: raise base to n-th power; n >= 0 */
int power(int base, int n)
{
int result = 1;
for (int i = 1; i <= n; ++i)
result *= base;
return result;
}resultstarts at 1 (any number to the power 0 is 1); the loop multiplies bybasen times.- Each call passes two arguments and gets an
intback to be formatted byprintf. - Negative exponents: return a floating value.
double power(double base, int exponent) {
double result = 1.0;
int positive_exp = (exponent < 0) ? -exponent : exponent; // absolute value
for (int i = 0; i < positive_exp; i++) {
result *= base;
}
return (exponent < 0) ? 1.0 / result : result;
}Parameters, arguments, prototype
- Parameters are variables named in the function's declaration; arguments are the values passed at call time, assigned to the parameters.
- A prototype such as
int power(int base, int n);placed beforemainsayspowerexpects two ints and returns an int. Parameter names are optional (int power(int, int);) but good names document the function. - Function definitions may appear in any order and in one or several source files, but a function cannot be split between files.
return
return expression;sends a value back; the return type in the declaration states which type. Any expression may followreturn.mainis a function like any other: it returns a value to its caller, the environment running the program. Zero means normal termination, non-zero signals unusual or erroneous termination.- A function need not return a value: use
voidas return type. - C also offers library functions (
printf,scanf,strlen, ...), and functions may call themselves (recursion), used for problems that split into smaller similar sub-problems: Recursion and its AnalysisA recursive algorithm solves an instance by calling itself on smaller instances until a base case; its cost is the sum of node costs in the recursion tree and its correctness is proved by induction.Recursion and its Analysis →.
Passing arguments: call by value
- In C all arguments are passed by value: the callee receives copies in temporary variables, so the originals are not affected.
- To modify the caller's variable, pass its address (a pointer): the caller provides
&var, the parameter is declared as a pointer and the variable is accessed through it. This gives "pass by reference" behavior (Puntatori in CUn puntatore contiene un indirizzo di memoria; operatori & e *, NULL, puntatori come parametri per modificare variabili del chiamante, aritmetica dei puntatori, legame tra array e puntatori, const, puntatori a puntatori.Puntatori in C →). - For arrays, the argument is the address of the first element: no copying of elements.
- Structs can be passed by value or by pointer (see Command-Line Arguments and StructsHow main receives command-line arguments (argc, argv), converting them with atoi and strtol, parsing options with getopt, and grouping data with struct, typedef and union.Command-Line Arguments and Structs →).
- Functions can also encapsulate error-handling code, keeping the main flow clean.
- Slide exercises: sum of two ints (by value);
void inc_value(int x)(changes a copy only) versusvoid inc_ref(int *x); swap two ints through pointers;void scale(int *arr, int n, int k)multiplying each element by k;int count_char(char *s, char c); withstruct Point { int x, y; };writevoid move(Point *p, int dx, int dy)(in place) andPoint moved(Point p, int dx, int dy)(returns a copy).
Function pointers
A function pointer stores the address of a function and calls it indirectly.
#include <stdio.h>
void greet() {
printf("Hello, world!\n");
}
int main() {
void (*func_ptr)(); // pointer to a function with no arguments returning void
func_ptr = greet; // address of the function
func_ptr(); // indirect call
return 0;
}Syntax: return_type (*pointer_name)(parameter_types);, e.g. int (*operation)(int, int);. As a parameter:
int add(int a, int b) { return a + b; }
int operate(int x, int y, int (*func)(int, int)) { return func(x, y); }
int main() {
int result = operate(5, 3, add);
printf("Result: %d\n", result); // Result: 8
return 0;
}- Use: dynamic behavior, callbacks (inversion of control), replacing large
switch/if-elsechains with jump tables, modular state machines and event handlers. - Initialization with a function name;
&is optional. Call asfp(2, 3)or(*fp)(2, 3): both valid. - Reading declarations:
int (*fp)(double)is a pointer to a function taking a double and returning an int;int (*h(void))(double)is a function h returning such a pointer.typedefsimplifies complex declarations. - Pitfalls: mismatched callback signatures (undefined behavior, crashes or wrong results, e.g. in sorting), not using
constfor read-only tables, confusing pointers to functions with pointers to pointers. - Slide exercise: implement
int add(int,int),int mul(int,int)andint apply(int (*op)(int,int), int a, int b); choose the operation withgetopt():-o add|mul int1 int2(see Command-Line Arguments and StructsHow main receives command-line arguments (argc, argv), converting them with atoi and strtol, parsing options with getopt, and grouping data with struct, typedef and union.Command-Line Arguments and Structs →).
Versione ripasso
- Variables are declared before use, usually at the start of the function:
int fahr, celsius;. The deck announces scope rules but does not develop them: do not rely on these notes for scope. - Definition:
return-type name(params) { declarations; statements }. A prototype before use:int power(int base, int n);. Parameters are the names in the definition, arguments the values given at the call. return expr;sends a value back;voidif nothing is returned.mainreturns 0 for normal termination.- Worked example,
power(base, n): start fromresult = 1and multiply bybasen times. Thedoubleversion handles negative exponents with1.0 / result. - Recursion: a function calling itself on smaller similar problems (Recursion and its AnalysisA recursive algorithm solves an instance by calling itself on smaller instances until a base case; its cost is the sum of node costs in the recursion tree and its correctness is proved by induction.Recursion and its Analysis →).
- Everything is passed by value: the callee gets a copy. To modify the caller's variable, pass
&varand declare the parameter as a pointer (int *x) (Puntatori in CUn puntatore contiene un indirizzo di memoria; operatori & e *, NULL, puntatori come parametri per modificare variabili del chiamante, aritmetica dei puntatori, legame tra array e puntatori, const, puntatori a puntatori.Puntatori in C →). - An array argument is the address of its first element: its elements are not copied and can be changed.
- Structs can go by value (
Point moved(Point p, int dx, int dy), a copy) or by pointer (void move(Point *p, ...), changed in place) (Command-Line Arguments and StructsHow main receives command-line arguments (argc, argv), converting them with atoi and strtol, parsing options with getopt, and grouping data with struct, typedef and union.Command-Line Arguments and Structs →). - Function pointer:
int (*op)(int, int);, assigned withop = add;, called asop(2, 3). Passed as a parameter it gives callbacks, and it can replace longswitchchains. - Typical errors: expecting a by-value parameter to change the caller, forgetting the
&, wrong callback signature (undefined behavior), declaring a variable after the statements.