Salta al contenuto
Note per Studenti Miscellaneous Syntax - Enums, Typedef, Preprocessor and More Report

Miscellaneous Syntax - Enums, Typedef, Preprocessor and More

In questa pagina 8

A variable's scope is the part of the program where it can be accessed; two aspects matter: visibility and lifetime. Related notes: Pointers and Dynamic Memorypointers in C: address and dereference operators, pointer arguments, pointers to functions, and dynamic memory allocation with malloc, calloc, realloc and free, with the checks and exercises given in the course.Pointers and Dynamic Memory →, Arrays and Stringsarrays and strings in C: the equivalence between array indexing and pointer arithmetic, passing arrays to functions, string constants versus char arrays, strlen and strcpy written with pointers, multi-dimensional arrays, arrays of pointers and array initialization.Arrays and Strings →, 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 →.

Scope

Scope Where Notes
Block inside {} (loops, if...) visible only in that block
Function labels (used with goto) not reachable outside the function
File (global) outside every function visible from the declaration to the end of the file
Function prototype parameter names in a prototype only in the prototype, ignored afterwards
  • Local (automatic) variables exist only while the function is running, do not keep their value between calls, and contain garbage if not set.
c
int main() {
    int x = 10;                       // block scope of main
    if (x > 5) {
        int y = 20;                   // block scope of the if
        printf("x = %d, y = %d\n", x, y);
    }
    // printf("%d", y);               // error: y not accessible here
    return 0;
}
  • Label with function scope (the slide uses goto my_label; inside main).
  • Prototype: void display(int x, int y); then void display(int a, int b) { ... }: the names x and y have no relation with a and b.
  • Same-named locals in different functions are unrelated; parameters are local variables.

Global (external) variables

Defined outside any function, accessible from any function, kept permanently (they retain their values after the function that set them returns); can replace argument lists to share data.

c
#include <stdio.h>
int counter = 0;                   // global, file scope
void increment() { counter++; }
int main() {
    increment();
    printf("Counter: %d\n", counter);
    return 0;
}

Definition vs declaration

  • Definition: where the variable is created and storage is set aside (exactly once in the whole program). Initialization goes only with the definition.
  • Declaration: states the type, no storage. Written with extern.
  • Array sizes must be given in the definition and are optional in an extern declaration.
c
// File: file1.c
int globalVariable;              // definition
// File: file2.c  and  file3.c
extern int globalVariable;       // declaration
  • The extern can be omitted if the definition appears earlier in the same source file (common practice: definitions at the top, no extern). It is mandatory when the variable is used before its definition or in another file.
  • External variables and functions have external linkage: all references to the same name are the same thing. Functions are always external: C does not allow functions inside functions.
  • The scope of an external variable or function goes from its declaration to the end of the file.
  • Put extern declarations of variables and functions in a header file (.h) and #include it in every source file: a single copy to keep updated. Shared definition: extern int globalVar; in example.h, int globalVar = 0; in one .c file.
  • Pitfalls: multiple definitions of the same object cause linker errors; uninitialized automatic variables are indeterminate; define in one source file, declare extern in headers.
  • Avoid overusing globals: data connections become hidden and the program hard to change; but with many shared variables they are more convenient than long argument lists.

Storage classes

Class Meaning
auto default for locals; destroyed at the end of the block or function
static lifetime = whole program, scope limited to where defined
extern declares a global defined elsewhere
register hint to keep the variable in a CPU register

static

  • Keeps its value between calls, initialized only once, lifetime = whole run.
  • Inside a function: not accessible outside it.
  • At file level: internal linkage, visible only in that source file, cannot be reached from other files even with extern.
c
void exampleFunction() {
    static int staticVar = 0;
    staticVar++;
    printf("Static Variable: %d\n", staticVar);
}
// three calls print 1, 2, 3
  • Use static to hide internal state and avoid name clashes in modular programs (static int internalState = 0; in module.c is private to it). Each file may have its own static of the same name.
  • To share across files do not use static: define in one file, extern in the others.

register

  • A hint to use a CPU register (faster); the compiler may ignore it, and modern compilers allocate registers well on their own.
  • You cannot take its address with & (may be a compile error).
  • Same scope and lifetime as an automatic variable.
  • Uses: loop counters and heavily used variables in tight loops, embedded systems. Overuse can hinder compiler optimization; profile before relying on it.
c
register int i, sum = 0;
for (i = 1; i <= 100; ++i) sum += i;

Check yourself (questions from the slides, answers from the rules above)

  • Classify extern int a; static int b; int c; register int d; by scope, lifetime, default initialization: a is only a declaration of a global defined elsewhere (external linkage, static lifetime, zero if defined without initializer); b static lifetime, internal linkage, zero-initialized; c (at file level) external linkage, static lifetime, zero-initialized; d automatic, local, undefined (garbage) value.
  • Static local variable: block scope, static storage duration (true). extern int x; inside a function declares, does not define (false). File-scope variables are zero-initialized by default (true). register does not guarantee a register (false). The question on const at file scope and linkage is not covered by the slides.
  • A variable inside a block with no storage class: no linkage, automatic duration (b). File-scope static int v;: internal linkage (b). Correct pair: file-scope static, internal linkage (b).
  • int f(void) { int x = 0; static int y = 0; return ++x + ++y; } called three times returns 2, 3, 4 (x restarts at 0 each call, y keeps its value).
  • static int hdr_counter = 0; in a header included by several source files: each file gets its own private copy (internal linkage).

Block structure

C is not block-structured (no function inside a function), but variables are block-structured within a function: a declaration (with initializer) may follow the { of any compound statement.

  • Such variables hide same-named variables of outer blocks until the matching }.
  • An automatic variable declared and initialized in a block is initialized each time the block is entered.
  • Automatic variables and parameters also hide external variables and functions of the same name:
c
int x;
int y;
void f(double x) {
    double y;
    // here x is the double parameter, y the local double; outside f they are the external ints
}

Style: avoid names that hide outer names, too much risk of confusion.

Initialization

  • Without explicit initialization: external and static variables are zero; automatic and register variables have undefined (garbage) values.
  • int x = 1; char squote = '\''; long day = 1000L * 60L * 60L * 24L; /* milliseconds/day */
  • External and static: the initializer must be a constant expression, done once before the program starts.
  • Automatic and register: any expression, even a function call; it is shorthand for an assignment each time the block is entered:
c
int binsearch(int x, int v[], int n) {
    int low = 0;
    int high = n - 1;
    int mid;
    ...
}

Explicit assignments can be easier to read than initializers in declarations. Array and string initialization is in Arrays and Stringsarrays and strings in C: the equivalence between array indexing and pointer arithmetic, passing arrays to functions, string constants versus char arrays, strlen and strcpy written with pointers, multi-dimensional arrays, arrays of pointers and array initialization.Arrays and Strings →.

const and volatile

const declares variables that cannot be modified after initialization (a modification is a compile error): immutability, must be initialized at definition, symbolic names with meaning (const int DAYS_IN_WEEK = 7;), protection from accidental changes. Can be global.

c
const double PI = 3.14159;                    // global constant
void printCircleArea(double radius) {
    double area = PI * radius * radius;
    printf("Circle Area: %f\n", area);
}

const with pointers

Declaration Meaning
const int *ptr = &x; pointer to constant data: *ptr = 20 is an error, ptr = &y is allowed
int *const ptr = &x; constant pointer: *ptr = 10 is allowed, ptr = &y is an error
const int *const ptr = &x; constant pointer to constant data: neither can change

Error messages: assignment of read-only location '*ptr' and assignment of read-only variable 'ptr'.

const in functions

  • Parameter void display(const int value): the function cannot modify it.
  • Pointer parameter void printArray(const int *arr, int size): the function cannot modify the elements (arr[i] = 5; would be an error); useful with large structures passed by reference.
  • Return type const int getNumber(): signals a result that should not be modified, more meaningful with pointers.

Enumerations

c
enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
enum Days today = TUESDAY;
printf("Today is %d\n", today);       // prints 2

An enumeration is a set of named integer constants (enumerators), counted from 0 unless values are given. In the lab exercise, values are assigned explicitly (blond 1, brown 0, black 3, white 2), see Lab Exercises - Loops, Arrays, Structs and IOlab exercises on loops, arrays, strings, structs, enums and file input: the statements from the course slides with their hints, plus the one solution the slides give (string reversal with an exchange function).Lab Exercises - Loops, Arrays, Structs and IO →.

typedef: these slides do not treat it on its own; they only note (in the file I/O slides) that FILE is a type name, like int, defined with typedef in <stdio.h>, not a structure tag (see Files and Formatted IOfile access in C with the stdio functions: fopen modes, character, formatted, line and binary I/O, positioning, end-of-file and error handling, buffering, temporary files, remove and rename, plus the C++ file streams.Files and Formatted IO →).

volatile

Tells the compiler that a value can change at any time outside the program's control, so it must not optimize accesses: it is read from memory before each use instead of being cached in a register. Uses: hardware registers, variables modified by another thread or interrupt handler, signal handlers. const volatile int sensorValue; means the program cannot modify it but it can change externally.

c
volatile int interruptFlag = 0;
void ISR() { interruptFlag = 1; }          // simulates an interrupt
int main() {
    while (!interruptFlag) { }             // wait
    printf("Interrupt occurred!\n");
    return 0;
}

Without volatile the compiler might not re-read interruptFlag and loop forever.

The C preprocessor

A conceptually separate first step of compilation. The most used features: #include (insert a file's contents, handy for collections of #defines and declarations) and #define (replace a token by a sequence of characters). All directives start with #, which must be the first non-blank character (better in the first column).

c
#define name replacement text
Directive Description
#define substitutes a macro
#include inserts a header from another file
#undef undefines a macro
#ifdef true if the macro is defined
#ifndef true if the macro is not defined
#if tests a compile-time condition
#else alternative for #if
#elif #else and #if in one
#endif ends a conditional
#error prints an error message on stderr

#define vs const

  • #define is handled by the preprocessor (text substitution, no type); const by the compiler (a variable, with type checking, and pointers can be used on it).
  • #define token value: no terminating semicolon; const type name = value; has one.
  • const is generally preferred, but #define cannot always be replaced: it can take parameters (not type-checked) and can replace any text.

Macros with parameters

c
#define INCREMENT(x) ++x      // works with any type
char* ptr = "Example"; int x = 10;
printf("%s ", INCREMENT(ptr));   // xample
printf("%d", INCREMENT(x));      // 11

Arguments are not evaluated before expansion: use parentheses.

c
#define MULTIPLY(a, b) a* b
MULTIPLY(2 + 3, 3 + 5)         // expands to 2 + 3 * 3 + 5 = 16, not 40
#define MULTIPLY(a, b) (a) * (b)
MULTIPLY(2 + 3, 3 + 5)         // (2 + 3) * (3 + 5) = 40

#define square(x) x* x
36 / square(6)                 // 36/6*6 = 36
#define square(x) (x * x)
36 / square(6)                 // 36/(6*6) = 1
  • ## token pasting: #define merge(a, b) a##b then merge(12, 34) prints 1234.
  • # before a parameter turns the token into a string literal: #define get(a) #a then get(Example) gives "Example".
  • A macro can span several lines with \ at the end of each line except the last:
c
#define PRINT(i, limit) \
    while (i < limit) { \
        printf("Example "); \
        i++; \
    }
  • #undef MACRO_NAME removes a macro. In the slide example a macro div(x, y) hides the function div(float, float); after #undef div the function is called (and the function body there divides y by x, so the two outputs differ).

Conditional compilation

c
#if VERBOSE >= 2
printf("Trace Message");
#endif

#define DEBUG                           // comment it out to disable debug mode
#ifdef DEBUG
#define DEBUG_PRINT(msg) printf("Debug: %s\n", msg)
#else
#define DEBUG_PRINT(msg)
#endif
#ifndef RELEASE
#define RELEASE
#endif
  • Used to include or exclude code according to compile-time configuration.
  • Header guards: a header included more than once (directly or indirectly) causes redeclaration problems; #define, #ifdef, #ifndef prevent it.

Predefined macros

__FILE__ (source file), __DATE__ (compilation date), __TIME__ (compilation time), __LINE__ (line number).

c
printf("Current File :%s\n", __FILE__);
printf("Line Number :%d\n", __LINE__);

Recursion

A C function may call itself, directly or indirectly. Each invocation gets a fresh set of all its automatic variables, independent from the previous ones. Recursion does not save storage (a stack of values is kept) and is not faster, but the code is more compact and often easier to write, especially for recursively defined data structures like trees. See 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 → and Binary TreesA binary tree is an ordered tree where each node has at most two children (left and right); in a proper binary tree every internal node has exactly two, which gives the leaf count m = n - m + 1 and bounds linking height, leaves and nodes.Binary Trees →.

c
int factorial(int n) {
    if (n == 0 || n == 1) return 1;            // base case
    else return n * factorial(n - 1);          // n! = n * (n-1)!
}

int fibonacci(int n) {
    if (n == 0) return 0;                      // base cases
    else if (n == 1) return 1;
    else return fibonacci(n - 1) + fibonacci(n - 2);   // F(n) = F(n-1) + F(n-2)
}

// binary search on a sorted array
int binarySearch(int arr[], int low, int high, int target) {
    if (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == target) return mid;            // found
        if (arr[mid] > target)
            return binarySearch(arr, low, mid - 1, target);    // left half
        else
            return binarySearch(arr, mid + 1, high, target);   // right half
    }
    return -1;                                         // not found
}

In the slide main: factorial(5), fibonacci(6), and binarySearch on {2, 4, 6, 8, 10, 12, 14, 16} looking for 10, with size = sizeof(sortedArray) / sizeof(sortedArray[0]).

Exercises from the slides:

  1. void print_reverse(const char *s) prints a string in reverse using recursion; no loops, no additional arrays ("hello" prints olleh).
  2. int sum_digits(int n) returns the sum of the digits of a non-negative integer; base case n < 10 ? n : ... (sum_digits(907) is 16).

Versione ripasso

c
int x = 10;
if (x > 5) { int y = 20; }   // y is visible only inside the if
  • Global variables keep their value after the function returns. Define once (storage, initializer, exactly once in the program), declare with extern int g; where it is used. extern is optional when the definition comes earlier in the same file, mandatory when the variable is used before its definition or in another file. Put the extern declarations in a header and #include it; the definition goes in one .c file.
  • Two definitions of the same object give a linker error. Functions are always external: C has no functions inside functions.
  • External linkage: all references to the name are the same object. static at file level gives internal linkage: private to that source file, even extern from another file cannot reach it.
  • Storage classes: auto (default for locals, destroyed at the end of the block), static (lifetime = whole run), extern (declares a global defined elsewhere), register (a hint to use a CPU register).
  • static local counter: static int staticVar = 0; is initialized once and keeps its value between calls (three calls print 1, 2, 3). Use static to hide internal state of a module, but not to share across files.
  • register: only a hint, the compiler may ignore it; you cannot take its address with &. Typical use: loop counters.
  • Defaults: external and static variables are zero, automatic and register variables are garbage. External and static initializers must be constant expressions; automatic ones may be any expression.
  • Quiz rules from the slides: a static local has block scope and static duration; extern int x; inside a function declares; register guarantees nothing. int f(void) { int x = 0; static int y = 0; return ++x + ++y; } returns 2, 3, 4 over three calls. A static variable in a header gets a private copy in each file that includes it.
  • Block structure: an inner declaration hides an outer one of the same name until the closing }. A parameter or local hides a global of the same name. Automatic variables with an initializer are re-initialized at each entry of the block. Avoid names that hide outer names.
  • const values cannot be modified (a compile error) and must be initialized at the definition. const int *p fixes the data, int *const p fixes the pointer, const int *const p fixes both. const parameters protect the caller's data, e.g. void printArray(const int *arr, int size).
  • volatile tells the compiler the value can change outside the program's control, so every use is read from memory: for hardware registers, interrupt flags and variables changed by other threads. Without it, while (!interruptFlag) { } may never end. const volatile is read-only for the program only.
  • enum Days { SUNDAY, MONDAY, TUESDAY, ... }; names integer constants counted from 0, or from the explicit values given. enum Days today = TUESDAY; prints 2.
  • Preprocessor runs first: #include (insert a file), #define (substitute a token), #undef, #ifdef / #ifndef, #if, #else, #elif, #endif, #error. Directives start with # as the first non-blank character.
  • #define (text, no type, no ;) versus const (typed, checked by the compiler, pointers allowed): const is generally preferred, but #define can take parameters and replace any text.
  • Macros need parentheses: #define MULTIPLY(a, b) a* b gives MULTIPLY(2 + 3, 3 + 5) = 2 + 3 * 3 + 5 = 16; with (a) * (b) it gives 40. #define square(x) x* x makes 36 / square(6) equal 36; with (x * x) it is 1.
  • ## pastes tokens (merge(12, 34) is 1234); # makes a string (get(Example) is "Example"); a multi-line macro ends each line but the last with \. #undef removes a macro, after which a real function of the same name is called.
  • Conditional compilation: #if VERBOSE >= 2, #ifdef DEBUG to include debug code, #ifndef RELEASE. Header guards (#ifndef + #define) avoid double inclusion of a header.
  • Predefined macros: __FILE__, __DATE__, __TIME__, __LINE__.
  • Recursion (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 →, Binary TreesA binary tree is an ordered tree where each node has at most two children (left and right); in a proper binary tree every internal node has exactly two, which gives the leaf count m = n - m + 1 and bounds linking height, leaves and nodes.Binary Trees →): each call gets a fresh set of automatic variables. It needs a base case and a recursive case, and it is not faster nor smaller in memory, but the code is more compact. Examples: factorial(n) (n == 0 || n == 1 gives 1), fibonacci(n) with two base cases, binary search with mid = low + (high - low) / 2 on a sorted array (returns -1 when not found).
  • Exercises (no solutions on the slides): print_reverse(const char *s) in recursion with no loops and no extra arrays (hello prints olleh); sum_digits(907) = 16.
  • Typical errors: missing parentheses in macros, defining a global in a header included twice (linker error), forgetting the base case of a recursion, relying on register, using an extern declaration without a matching definition.

Teoria collegata