Primitive Data Types and Expressions
In questa pagina 7
C is statically typed: every variable must be declared with its type before use (usually at the start of the function, before executable statements). A declaration is a type plus a list of variables: int fahr, celsius;. The type fixes the range of values and the operations allowed. Choosing the wrong type gives unexpected behavior and errors.
Groups of types: basic, derived, enumeration, user-defined (struct, union), void. Structs and unions are in 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 →.
Basic types
| Type | Size (bytes) | Range / precision |
|---|---|---|
short |
2 | -32,768 to 32,767 |
int |
4 | -2,147,483,648 to 2,147,483,647 |
long |
8 (4 or 8 by platform) | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float |
4 | 6-7 decimal digits |
double |
8 | 15-16 decimal digits |
long double |
8, 12 or 16 | typically more than double |
- Sizes and ranges are machine/compiler dependent; use
sizeof(type)and<limits.h>(INT_MAX,INT_MIN). floatis single precision, with limited precision (some numbers are not represented exactly);doubleis used when higher accuracy is needed.- Integers overflow silently (see 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 →).
char
- One byte (256 values), stores letters, digits, symbols, control characters. Stored as a number via an encoding (ASCII, UTF-8):
'A'is 65,'B'is 66. - Assign with single quotes:
char myChar = 'A';. Escapes:'\n','\t'. - Chars can be compared and added/subtracted:
'A' < 'B'is true. - Strings are null-terminated char arrays;
'\0'marks the end.
bool
- C99 and later:
#include <stdbool.h>, valuestrue(1) andfalse(0).
#include <stdbool.h>
bool isEven(int number) { return (number % 2 == 0); }- In C any non-zero value is true, not only 1;
0is false. Older compilers may not supportbool: check compatibility and include the header. - You can use
&&,||,!with bool. - C++:
boolis built in; assigning1725or-19gives a warning and the value is stored as true.std::cout << std::boolalpha;printstrue/falseinstead of 1/0.
void
Absence of a type: functions that return no value (void functionName() { ... }) and pointers to unspecified data.
Derived types
Arrays
- Same-type elements in contiguous memory, fixed size set at declaration (
int numbers[5];), zero-based indexarray[index]. - Initialization:
int numbers[5] = {1, 2, 3, 4, 5};orint numbers[] = {1, 2, 3, 4, 5};(size inferred as 5). - Iterate with loops:
for (int i = 0; i < 5; i++) printf("%d\n", numbers[i]); - Out-of-bounds access is undefined behavior (memory corruption, crashes). C arrays do not store their size: track it yourself. Initialize arrays to avoid garbage values.
- Multidimensional arrays are arrays of arrays (a 2D array is a table). Strings are char arrays. Library helpers:
memcpy(),memset()(the slide also listssort()).
Pointers
- A pointer stores the memory address of another object. Declare with
*; take addresses with&.
int value = 42;
int *ptr = &value; // ptr points to value- Pointer arithmetic: incrementing moves to the next object of its type (useful on arrays);
NULLmeans "points to nothing" (check before use). - The array name acts as a pointer to its first element;
*(p + i)accesses element i. Arrays and pointers differ in allocation andsizeof, so they are not always interchangeable. - Pointers refer to arrays and structs, support dynamic allocation (
malloc(),calloc(),realloc()) and function pointers (see Functions, Variables and ScopeHow to declare variables, define and call functions with prototypes and return values, pass arguments by value or through pointers, and use function pointers.Functions, Variables and Scope →). - Pitfalls: uninitialized pointers, dangling pointers (freed memory), memory leaks, NULL dereference. Always initialize, check NULL, pair
mallocwithfree. - Full treatment: 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 →, Gestione della memoria in CSegmenti di memoria di un processo (codice, dati statici, stack, heap); durata delle variabili; allocazione dinamica con malloc, calloc, realloc e free; errori classici: memory leak, dangling pointer, double free, buffer overflow; strumenti di controllo.Gestione della memoria in C →.
Enumerations
enum Color { RED, GREEN, BLUE }; // 0, 1, 2
enum Color favoriteColor = GREEN;
enum Days { MONDAY = 1, TUESDAY = 2, WEDNESDAY = 3 /* ... SUNDAY = 7 */ };- Named integer constants, sequential from 0 unless given explicitly; an explicit value affects the following ones (
LOW = 10, MEDIUM, HIGHgives 10, 11, 12 by the sequential rule). - Enumerators are read-only constants; compare with
==,!=or use inswitch. Size is usuallyintbut implementation-defined:sizeof(enum Color). - Versus
#define: enums group related constants under one type, allow compiler type checking, and keep names in the symbol table (easier debugging); macros are untyped. - Pitfalls: bit flags without explicit values, size varies across compilers, out-of-range values are undefined behavior.
- Slide exercises:
switchover an enum printing names;typedef enum { JAN, ..., DEC, MONTHS_COUNT } Month;thenint days_in_month[MONTHS_COUNT]for a non-leap year; true/false questions on enums.
Arithmetic operators
+ - * /and%(remainder). Integer/truncates:15 / 4is 3;15 % 4is 3.++and--add or subtract 1; compound assignmentx += ymeansx = x + y.- If both operands are integers an integer operation is done; if one is floating and one integer, the integer is first converted to floating point. Writing constants with a decimal point (
5.0/9.0) emphasizes their floating nature. - Slide exercises: with
a = 7,b = 3print sum, difference, product,a / b,a % b; printa / b,(float)a / b,a / (float)b,a / 3.0; average of two integers as a float with one decimal (5 and 6 give 5.5); integer averageavgofx = 5,y = 8; seconds to min:sec (s = 125, using division and modulo); predictint a = 3; int b = ++a * 2; int c = a++ + b;; predict5/2*2,5*(2/2),5/2*2.0; normalizeang = -725to [0, 360) with only+ - * / %.
Expression evaluation rules
- C arithmetic is not always the one we do by hand.
3/2*2: evaluated left to right,3/2is integer division (1), so the result is 2, not 3. With reals,3.0/2.0*2.0is 3. - Operands should have the same type: in
3.0 + 2the integer becomes real,3.0 + 2.0 = 5.0. - Cast:
(type name) expressionconverts the expression as if it were assigned to a variable of that type. Example:sqrtexpects adouble, so for an integer n usesqrt((double) n). sizeofis a unary operator returning the bytes needed for a type or variable:sizeof(int)is 4,char name[20]; sizeof(name)is 20.- Precedence and assignments inside
?:: see exercise in 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 →. Use parentheses to clarify.
Comparison operators
==equal,!=not equal,>,<,>=,<=. Result: 1 (true) or 0 (false).==compares,=assigns: confusing them is a classic bug (the slide says=in a condition gives a syntax error; the pitfalls slide says it assigns instead of comparing, so it is a logic bug at least).- Usable on numbers, chars and pointers.
- Chained
x == y == zdoes not test "all equal"; write a correct boolean (exercise). - Slide exercises: predict
a == b,a != b,a == cfor 7, 7, 9;is_evenusing%and==forn = 14; is((p / q) * q + (p % q)) == ptrue for 10 and 3.
Logical operators
&&AND: true only if both are true.||OR: true if at least one is true.!NOT: inverts (unary).- Truth table (A, B -> A and B, A or B, not A):
- 0, 0 -> 0, 0, 1
- 0, 1 -> 0, 1, 1
- 1, 0 -> 0, 1, 0
- 1, 1 -> 1, 1, 0
- Short-circuit: in
&&, if the first operand is false the second is not evaluated; in||, if the first is true the second is not evaluated. - Combine with parentheses:
if ((m > 0 && n > 5) || (m < 0 && n < 10)). - Results are 0 for false, non-zero for true. Pitfalls:
=vs==; any non-zero is true; ambiguous expressions without parentheses. - Slide exercises: "all equal" without
a == b == c;ok = 1only if age in [0, 120] and height positive; exactly one of p, q non-zero using only&&,||,!;q = x / yonly wheny != 0andx % y == 0, one line, using short-circuit.
Bitwise operators
Operate bit by bit on integers (flags, hardware registers, compression, encryption, image processing, packing flags in one integer).
&AND: 1 if both bits are 1.1010 & 1101gives1000.|OR: 1 if at least one is 1.1010 | 1101gives1111.^XOR: 1 if the bits differ.1010 ^ 1101gives0111.~NOT: inverts all bits.~1010gives0101(4-bit view).<<left shift: low bits filled with zero, bits out on the left discarded; multiplies by 2 to the shift count.1010 << 2gives101000.>>right shift: divides by 2 to the shift count; unsigned fills with zeros, signed fills with the sign bit.1010 >> 2gives10. Operands undergo the usual integer promotions before a shift.- Careful: incorrect use gives unexpected results or undefined behavior.
- Slide exercises (signatures):
int is_odd(int x)with AND;unsigned set_bit/clear_bit/toggle_bit(unsigned x, unsigned pos);unsigned get_bits(unsigned x, unsigned lo, unsigned hi)(bits hi:lo right-justified);unsigned int popcount(unsigned int x);int is_power_of_two(unsigned int x)(0 is not a power of two);unsigned char reverseUC(unsigned char uc)without loops.
Versione ripasso
- C is statically typed: declare every variable with its type before use (usually at the start of the function), e.g.
int fahr, celsius;. The type fixes the range and the allowed operations. - Basic types:
short2 B,int4 B,long4 or 8 B,float4 B (6-7 digits),double8 B (15-16 digits). Check withsizeofand<limits.h>. Integers overflow silently (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 →). charstores a code:'A'is 65,'A' < 'B'is true.boolneeds<stdbool.h>; in C any non-zero value is true.voidmeans no value.- Arrays: same-type elements in contiguous memory, fixed size, zero-based.
int numbers[] = {1, 2, 3, 4, 5};infers the size. C does not store the length and does not check bounds: out-of-range access is undefined behavior, so track the size yourself. - Pointers:
int value = 42; int *ptr = &value;.*declares and dereferences,&takes the address.*(p + i)is element i of an array, and the array name acts as a pointer to its first element, althoughsizeoftells them apart.NULLmeans "points to nothing": check before use (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 →, Gestione della memoria in CSegmenti di memoria di un processo (codice, dati statici, stack, heap); durata delle variabili; allocazione dinamica con malloc, calloc, realloc e free; errori classici: memory leak, dangling pointer, double free, buffer overflow; strumenti di controllo.Gestione della memoria in C →). - Pitfalls of pointers: uninitialized pointers, dangling pointers to freed memory, memory leaks,
NULLdereference. Pair eachmallocwith afree. - Enumerations:
enum Color { RED, GREEN, BLUE };gives 0, 1, 2;enum Days { MONDAY = 1, TUESDAY = 2 };and an explicit value affects the following ones (LOW = 10, MEDIUM, HIGHgives 10, 11, 12). Unlike#definethey group constants under one type and allow type checking. - Arithmetic:
+ - * / %; integer/truncates (15 / 4is 3,15 % 4is 3);x += ymeansx = x + y. Mixed integer and real operands: the integer is converted to floating point first. - Evaluation is left to right:
3/2*2is 2 (the first division is integer),3.0/2.0*2.0is 3,5/2*2.0is 4.0. The slides'int a = 3; int b = ++a * 2; int c = a++ + b;tests the order of increments. - Cast:
(type) expression, e.g.sqrt((double) n)for an integern.sizeofis a unary operator:sizeof(int)is 4,char name[20]; sizeof(name)is 20. - Comparisons
== != > < >= <=give 1 (true) or 0 (false).==compares,=assigns: in a conditionif (x = 5)is a logic bug. Never chainx == y == zto test "all equal": writea == b && b == c. - Logical operators:
&&true only if both are true,||true if at least one is,!inverts. Both&&and||short-circuit: inq = x / yguarded byy != 0 && x % y == 0, the division is not reached whenyis zero. Parenthesize:((m > 0 && n > 5) || (m < 0 && n < 10)). - Bitwise on integers:
&(1 if both bits are 1),|(1 if at least one),^(1 if different),~(inverts). Examples:1010 & 1101 = 1000,1010 | 1101 = 1111,1010 ^ 1101 = 0111,~1010 = 0101(4 bits).<<multiplies by 2 to the shift count,>>divides by it (unsigned fills with zeros, signed with the sign bit):1010 << 2 = 101000,1010 >> 2 = 10. - Typical errors: integer overflow unchecked, integer division where a real is needed,
=in place of==, array index out of range, uninitialized pointer,x == y == zused as "all equal".