Variable Assignment and Initialization

Assignment vs Initialization

Assignment

Gives a value to an already-existing variable:

int x;      // Variable created but uninitialized
x = 5;      // Assignment - gives x the value 5

Initialization

Gives a variable its initial value when it's created:

int x = 5;  // Initialization - x gets value 5 when created

Types of Initialization

Copy Initialization

Uses the equals sign:

int x = 5;
double pi = 3.14159;
char grade = 'A';

Direct Initialization

Uses parentheses:

int x(5);
double pi(3.14159);
char grade('A');

Uniform Initialization (C++11)

Uses braces - preferred for new code:

int x{5};
double pi{3.14159};
char grade{'A'};

Multiple Assignment

You can assign the same value to multiple variables:

int a, b, c;
a = b = c = 10;  // All three variables get value 10

Assignment Returns a Value

Assignment operations return the assigned value:

int x, y;
x = (y = 5);    // y gets 5, then x gets 5

Best Practices

  • Always initialize variables when you declare them
  • Use uniform initialization {} when possible
  • Don't chain assignments unless necessary
  • Initialize with meaningful values

Common Mistakes

// Bad - uninitialized variable
int count;
count = count + 1;  // Undefined behavior!

// Good - properly initialized
int count = 0;
count = count + 1;  // count is now 1