C ยท Chapter 7 of 45

C Variables

A variable is a named location in memory used to store a value. In C, every variable must be declared with a specific type before it can be used, and that type never changes.

Variable names must start with a letter or underscore, can contain digits, and cannot be a reserved keyword. Choosing clear variable names makes your code much easier to read.

Syntax
type name = value;

Declaring and initializing

A declaration reserves memory of the right size for a type, such as `int age;`. You can also initialize a variable with a value at the same time, like `int age = 25;`.

Naming rules

Names are case-sensitive and can include letters, digits and underscores, but cannot start with a digit. Avoid C keywords like int, return or for as variable names.

Example 1 (c)
#include <stdio.h>

int main() {
  int age = 25;
  float price = 9.99;
  printf("%d %.2f\n", age, price);
  return 0;
}
Output
25 9.99

Two variables of different types are declared, initialized and printed.

Example 2 (c)
#include <stdio.h>

int main() {
  int x, y;
  x = 5;
  y = 10;
  printf("Sum: %d\n", x + y);
  return 0;
}
Output
Sum: 15

Multiple variables of the same type can be declared on one line, then assigned separately.

Key points

  • Every variable in C has a fixed, declared type.
  • Variables can be declared and initialized in one statement.
  • Names are case-sensitive and cannot start with a digit.
  • Uninitialized local variables hold indeterminate garbage values.
๐Ÿ’ก Note: Always initialize your variables to avoid reading unpredictable garbage values.

๐Ÿ“ Quick Quiz

1. What must you specify when declaring a variable in C?

2. Which is a valid C variable name?

3. What happens if you use an uninitialized local variable?