Salta al contenuto
Note per Studenti Primitive Data Types and Expressions Report

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

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>, values true (1) and false (0).
c
#include <stdbool.h>
bool isEven(int number) { return (number % 2 == 0); }
  • In C any non-zero value is true, not only 1; 0 is false. Older compilers may not support bool: check compatibility and include the header.
  • You can use &&, ||, ! with bool.
  • C++: bool is built in; assigning 1725 or -19 gives a warning and the value is stored as true. std::cout << std::boolalpha; prints true/false instead 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 index array[index].
  • Initialization: int numbers[5] = {1, 2, 3, 4, 5}; or int 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 lists sort()).

Pointers

  • A pointer stores the memory address of another object. Declare with *; take addresses with &.
c
int value = 42;
int *ptr = &value;   // ptr points to value

Enumerations

c
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, HIGH gives 10, 11, 12 by the sequential rule).
  • Enumerators are read-only constants; compare with ==, != or use in switch. Size is usually int but 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: switch over an enum printing names; typedef enum { JAN, ..., DEC, MONTHS_COUNT } Month; then int days_in_month[MONTHS_COUNT] for a non-leap year; true/false questions on enums.

Arithmetic operators

  • + - * / and % (remainder). Integer / truncates: 15 / 4 is 3; 15 % 4 is 3.
  • ++ and -- add or subtract 1; compound assignment x += y means x = 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 = 3 print sum, difference, product, a / b, a % b; print a / 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 average avg of x = 5, y = 8; seconds to min:sec (s = 125, using division and modulo); predict int a = 3; int b = ++a * 2; int c = a++ + b;; predict 5/2*2, 5*(2/2), 5/2*2.0; normalize ang = -725 to [0, 360) with only + - * / %.

Expression evaluation rules

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 == z does not test "all equal"; write a correct boolean (exercise).
  • Slide exercises: predict a == b, a != b, a == c for 7, 7, 9; is_even using % and == for n = 14; is ((p / q) * q + (p % q)) == p true 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 = 1 only if age in [0, 120] and height positive; exactly one of p, q non-zero using only &&, ||, !; q = x / y only when y != 0 and x % 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 & 1101 gives 1000.
  • | OR: 1 if at least one is 1. 1010 | 1101 gives 1111.
  • ^ XOR: 1 if the bits differ. 1010 ^ 1101 gives 0111.
  • ~ NOT: inverts all bits. ~1010 gives 0101 (4-bit view).
  • << left shift: low bits filled with zero, bits out on the left discarded; multiplies by 2 to the shift count. 1010 << 2 gives 101000.
  • >> right shift: divides by 2 to the shift count; unsigned fills with zeros, signed fills with the sign bit. 1010 >> 2 gives 10. 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

Teoria collegata