Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 135 ยท Variables and Types

Variables

Learn how C variables work - declaring and initializing them, assigning new values, why uninitialized variables are dangerous, and a first look at scope.

A variable is a named piece of memory that holds a value. When you write int score = 0;, you ask the compiler for enough memory to store an integer, give that memory the name score, and put 0 in it. Later statements can read the value, change it, and use it in calculations. Almost every line of a real program involves variables.

C is stricter about variables than languages like Python or JavaScript. Every variable has a type that's fixed when you declare it, you must declare a variable before you use it, and C doesn't automatically give local variables a starting value. That last rule causes some of the most confusing bugs beginners meet, so this lesson spends time on it.

Declaring a variable

A declaration introduces a variable: its type, then its name, then a semicolon.

C
int age;          /* a whole number */
double price;     /* a number with a fractional part */
char initial;     /* a single character */

The type tells the compiler how much memory to reserve and how to interpret the bits stored there. You'll meet all the types in Data Types. For now, int, double and char are enough.

The name must follow the identifier rules from Keywords and Identifiers: letters, digits and underscores, not starting with a digit, not a keyword.

Initializing a variable

Giving a variable a value as part of its declaration is called initialization. It's what you should do almost every time:

C Declaring and initializing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The value on the right of = is the initializer. It can be a literal like 2026, or any expression, including other variables and function calls:

C
int width = 8;
int height = 5;
int area = width * height;   /* 40 */

Notice the different literals: whole numbers (2026), numbers with a decimal point (21.5), single characters in single quotes ('B'), and text in double quotes ("Lisbon"). const char *city is how C stores a pointer to a piece of text; Strings explains it properly.

Assignment: changing a value

After a variable exists, the = operator assigns it a new value. The old value is simply replaced:

C Assigning new values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints 3, 2, 10 and finally 16. Read lives = lives - 1 as "compute lives - 1 using the current value, then store the result in lives". The = in C is an action, not a statement of mathematical equality. Comparing two values for equality uses ==, which you'll meet in Comparison and Logical Operators. The shortcuts += and ++ are covered in Assignment and Increment Operators.

Initialization and assignment look similar but are different things. Initialization happens once, when the variable is created; assignment can happen any number of times afterwards. The difference matters later: const variables and arrays can be initialized but not assigned.

Declaring several variables

You can declare several variables of the same type in one declaration, separated by commas:

C
int x = 0, y = 0, z = 0;   /* three ints, all initialized */
int min, max = 100;        /* careful: only max is initialized! */

The second line is a classic trap: the = 100 belongs to max alone, and min has no value. Many style guides recommend one declaration per line, which avoids the confusion and gives each variable room for a comment.

Uninitialized variables are dangerous

What does a local variable contain if you don't initialize it? Whatever happened to be in that memory before. The C standard says the value is indeterminate, and using it is undefined behavior for most types: the program might print 0 one day and 32767 the next, behave differently with optimizations on, or (rarely) crash.

This example has the bug on purpose. Compile it and read the warning instead of trusting the output:

C Using an uninitialized variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

GCC warns 'total' is used uninitialized (-Wuninitialized). The number the program prints is not reliably 20. On our server it may well print 20, just because the memory happened to hold zero, but other compilers, settings or surrounding code can give a different result. Change the declaration to int total = 0; and the warning goes away and the total is always 20.

Warning: The compiler can't detect every use of an uninitialized variable, especially when the variable is passed to a function or set inside some branches of an if and not others. The reliable defense is a habit: initialize every variable when you declare it. If there's no meaningful value yet, use 0, 0.0 or nullptr/NULL.

There's one exception to the rule. Variables declared outside any function (global variables) and static variables are automatically initialized to zero. Local variables inside functions are not. You'll see why in Memory Layout of a C Program.

Where to declare variables

In C89, all declarations had to come at the start of a block, before any statements. That's why old C code often begins functions with a long list of declarations. Since C99, you can declare a variable anywhere in a block, including in the header of a for loop. Modern style declares each variable as close as possible to where it's first used, ideally at the moment you can give it a real value:

C Declaring close to first use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

total_kg is declared at the point where its value is known, so it never exists in an uninitialized state. The loop counter i exists only inside the for loop. Reading from the user is covered in Reading Input with scanf and fgets.

A first look at scope

A variable's scope is the part of the program where its name can be used. The basic rule: a variable declared inside a block { } is visible from its declaration to the end of that block. A variable declared outside all functions is global: visible to every function below it in the file.

C Local and global variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The global visits counts 1, 2, 3 across calls, while local_count is created fresh (as 1) on each call. The visits declared in main is a separate local variable that shadows (hides) the global from that point on, so the last line prints 100. Shadowing is legal but easy to misread; GCC can warn about it with -Wshadow.

Use globals sparingly. Any function can change them, which makes bugs hard to trace. Passing values to functions as parameters is usually clearer; see Functions. Scope, lifetime and static are covered thoroughly in Scope and Storage Classes.

Swapping two variables

A small but classic exercise shows that assignment overwrites values. To swap a and b, you need a temporary variable to hold one value while the other is copied:

C Swapping with a temporary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Without temp, writing a = b; b = a; would leave both variables equal to 9, because the first assignment destroys the original value of a.

C23: letting the compiler infer the type

C23 gave the old auto keyword a new job: in a declaration with an initializer, auto means "use the type of the initializer". It mainly helps in macros and with long type names. In everyday code, writing the type explicitly is usually clearer:

C auto type inference (C23)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice the surprise in the last line: letter is 4 bytes, because in C a character constant like 'x' has type int, not char. Surprises like this are one reason to prefer explicit types. auto with this meaning needs a C23 compiler (GCC 13+, Clang 18+).

A variable's three properties

Every variable has:

  • A name, which you use in your code.
  • A type, which decides its size, the values it can hold and the operations allowed on it. sizeof tells you the size in bytes.
  • A value, stored in memory at some address. You can print the address with %p and &name, which you'll use constantly once you reach Pointers.
C
int score = 70;
printf("score = %d, size = %zu bytes, address = %p\n",
       score, sizeof score, (void *)&score);

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? int a = 4; int b = a; a = 10; printf("%d", b);

    b got a copy of a's value (4) when it was initialized. Changing a later doesn't affect b.
  2. 2. In int low, high = 50;, which variables are initialized?

    Each initializer belongs to one declarator. = 50 applies to high only; low is left uninitialized.
  3. 3. What value does an uninitialized local int variable have?

    Local variables aren't initialized automatically. Their value is indeterminate, and using it is undefined behavior. Global and static variables, in contrast, start at zero.
  4. 4. What does this print? int x = 7; x = x * 2; x = x - 4; printf("%d", x);

    x starts at 7, becomes 14 after doubling, then 10 after subtracting 4.
  5. 5. A global int n = 1; exists. Inside main you write int n = 2; and print n. What appears?

    The local n shadows the global inside main, so n refers to the local variable with value 2. Declaring a local with the same name as a global is legal.

Summary

  • A variable is a named, typed piece of memory: declare it with a type and a name, like int count;.
  • Initialize every variable when you declare it (int count = 0;); uninitialized locals hold indeterminate values, and reading them is undefined behavior.
  • = assigns a new value, replacing the old one; initialization happens once, assignment any number of times.
  • Since C99, declare variables close to their first use, including loop counters in for headers.
  • A variable's scope runs from its declaration to the end of its block; globals and static variables start at zero; a local can shadow a global.
  • C23 auto infers a type from the initializer, but explicit types are usually clearer.

Next: Data Types, where you'll learn which types C offers and how big they are.