Variables in C

To store and manipulate data in a program, it is necessary to use variables.

In this lesson we will see how to use variables in the C language. We will learn how to declare, assign, and use variables of type int and double.

Variables

Up until now, we have implemented simple programs that printed messages to the screen. Programs rarely limit themselves to just this. In reality, even a simple program performs various calculations and processes data. For this reason, computers are referred to as data processors or calculators.

Therefore, if the calculations or operations to be performed are more or less complex, it becomes necessary to store intermediate results. Just like when solving a math problem on paper: we write down intermediate results so we don't forget them.

In computer science, to store intermediate results or the data to be processed, we use variables. A variable is a memory location that the programmer associates with a label, a symbolic name, to be able to refer to it within the program. At any moment, the programmer can assign a value to the variable and can read the value contained in it.

The name variable comes precisely from the fact that the value it contains can vary over time.

Definition

Variable

A variable is a memory location associated with a symbolic name.

The main operations that can be performed on a variable are:

  • Declaration: associating a symbolic name with a memory location.

  • Assignment: writing a value into the variable.

  • Reading: reading the value stored in the variable.

Type of a Variable

The C language is known for being a strongly typed language. This means that every variable must be associated with a type. The type of a variable determines what kind of data it can contain and what operations can be performed on it.

There are various types of variables in C. For now, we will focus on just two types: int and double.

The types int and double are numeric types; variables of these types allow you to store numbers. The choice between these two types determines the range of numbers that can be represented and their precision.

For example, a variable of type int (short for integer) can store whole numbers, meaning numbers without a decimal part. A variable of type double can store numbers with a decimal part, that is, real numbers.

We will study variable types in detail in a dedicated chapter. For now, we will limit ourselves to using int for whole numbers and double for real numbers.

Definition

Type of a Variable

The type of a variable determines the kind of data it can contain and the operations that can be performed on it.

Declaring a Variable

Before a variable can be used, it must be declared. Declaring a variable means describing its type and name to the compiler.

The syntax to declare a variable is as follows:

type name;

For example:

int number;
double height;

In the code above, we declared two variables:

  • number of type int;
  • height of type double.

If we want to declare multiple variables of the same type, we can do so on a single line, separating the names with commas:

int a, b, c;

As we can see, variable declarations must end with a semicolon ;.

At this point, we can extend the general structure of a C program as seen in the dedicated lesson, like this:

directives

int main() {
    declarations
    statements
}

In other words, we have added the declarations section where we will declare the variables to be used in the program. This is true for any C program we want to write.

Furthermore, the structure of the main function, as we will see, is valid for any function. We always declare the variables to be used and then write the statements to be executed.

Definition

Variable Declaration

The declaration of a variable consists of describing its type and name to the compiler.

The syntax to declare a variable is as follows:

type name;

Assigning a Variable

We can assign a value to a variable, after it has been declared, using the assignment operation.

The syntax is very simple:

name = value;

So, for example, if we have a variable number of type int, we can assign it the value 42 like this:

number = 42;

The number on the right side of the = symbol is called a literal constant.

In C, to assign a value to a variable, the variable must have already been declared. It is not possible to assign a value to a variable that has not yet been declared, because from the compiler's point of view, the variable does not exist at that moment.

So, we can write:

/* Correct */
int number;
number = 42;

But we cannot write:

/* Incorrect */
number = 42;
int number;

For variables of type double, we can assign a decimal value:

double height;
height = 1.75;
Definition

Variable Assignment

The assignment of a variable consists of assigning a value to a variable.

The syntax for assigning a value to a variable is as follows:

name = value;

Using a Variable

Once we have declared a variable and assigned it a value, we can use it within the program.

To use, or more precisely to read the content of a variable, simply write the name of the variable itself.

Fortunately, the C language is designed to support mathematical formulas, known as expressions. Therefore, we can write expressions involving variables and constants and combine them using arithmetic operators.

For example, suppose we have two variables:

int a, b;

We can write an expression like:

a = 5;
b = a + 10;

In the above code, we first assigned the value 5 to the variable a. Then we used its value in an expression to assign b the value a + 10, i.e., 5 + 10.

We will study expressions in detail in the appropriate chapter. For now, it's enough to know that we can write mathematical expressions in C using variables, constants, and the following arithmetic operators:

  • + for addition
  • - for subtraction
  • * for multiplication
  • / for division

We can also write more complex expressions:

int a, b, c;
a = 5;
b = 10;
c = a + b * 2;

C expressions also support parentheses, which allow us to change the order of evaluation of operations:

int a, b, c;
a = 5;
b = 10;
c = (a + b) * 2;
Definition

Using a Variable

To use a variable, just write its name inside an expression.

Initialization

The C language is a low-level language. This means that the programmer has full control over the computer's memory.

This also has consequences. For example, when we declare a variable, we cannot assume what value it contains. In other words, the value contained in a newly declared variable is undefined.

Suppose we declare a variable number of type int:

int number;

The value contained in number is undefined. It could be 0, 1, -1, 42, 1000, 123456789, ... or any other value. The C compiler does not initialize variables for us with a default value.

Therefore, if we write the following code:

int number;
int double_value;

double_value = number * 2;

The value of double_value will be unknown and may vary from execution to execution of the program.

You must always assign a value to variables after they have been declared. For example:

int number;
int double_value;

number = 5;
double_value = number * 2;

This way, the value of double_value will always be 10.

To simplify the writing of a program, in C it is possible to initialize a variable at the moment of its declaration. The syntax is as follows:

type name = initial_value;

For example:

int number = 5;
int double_value = number * 2;

In this way, we reduced the number of lines of code and made the program more readable.

Definition

Variable Initialization

Initialization of a variable means assigning an initial value to a variable at the time of its declaration.

The syntax to initialize a variable is:

type name = initial_value;

You must be careful when declaring multiple variables of the same type on a single line. In such cases, each variable must be initialized individually.

For example:

int a = 5, b = 10, c = 20;

If we had written:

int a, b, c = 20;

We would have only initialized the variable c to 20. The variables a and b would remain uninitialized.

Definition

Multiple Initialization

When declaring multiple variables of the same type on a single line, each variable must be initialized individually.

The syntax is:

type name1 = value1, name2 = value2, ..., nameN = valueN;

Printing the Value of a Variable

One of the most common operations in a program is printing the value of a variable to the screen. When writing a program that performs calculations, it's necessary to show intermediate or final results.

To print the value of a variable to the screen, we use the printf function, which we've already used to print messages.

The printf function is very versatile. To understand how to use it, let's analyze the following example:

int number = 42;
printf("The value of number is %d\n", number);

Notice a few things:

  1. We passed two arguments to the printf function. The first argument is a string, a sequence of characters enclosed in double quotes.
  2. The second argument is the value of the variable number.
  3. The string contains the text we want to print to the screen. Additionally, it includes a placeholder indicated with %d. This placeholder will be replaced by the value of the second argument.

The technical name for the %d placeholder is format specifier. There are several of them, and we will analyze them in detail in the next lessons.

When the printf function is executed, it replaces the %d placeholder with the value of the variable number and prints the result to the screen. Therefore, the following output will be produced:

The value of number is 42

If instead we wanted to print the value of a variable of type double, we would have to use the %f format specifier:

double height = 1.75;
printf("The value of height is %f\n", height);

In this case, the output would be:

The value of height is 1.750000

Finally, instead of the name of a variable, we could have used an expression:

int a = 5, b = 10;
printf("The sum of a and b is %d\n", a + b);

In general, there is no limit to the number of arguments we can pass to the printf function. We can pass any number and any type of arguments. The important thing is that the string contains as many placeholders as there are subsequent arguments.

As an example, let's look at the following program that calculates the area of a rectangle:

#include <stdio.h>

int main() {
    double base = 5.0;
    double height = 3.0;

    double area = base * height;

    printf("The area of the rectangle with base %f and height %f is %f\n",
           base, height, area);

    return 0;
}

In this program, we used three %f format specifiers to print three values of type double. Additionally, we split the printf statement across multiple lines to make it more readable. This is not a problem in C; we can write statements across multiple lines with no issue. The important thing is that the statement ends with a semicolon ;.

In Summary

In this lesson, we introduced the fundamental concept of variables in the C language. We have seen that:

  • A variable is a memory location associated with a symbolic name.
  • Every variable has a type that determines the kind of data it can hold and the operations that can be performed on it.
  • A variable must be declared before it can be used.
  • After a variable has been declared, we can assign it a value.
  • A variable can be used within an expression.
  • The value contained in a newly declared variable is undefined.
  • We can initialize a variable at the time of its declaration.
  • To print the value of a variable to the screen, we use the printf function.

In the next lesson, we will see how to ask the user to input a value from the keyboard and store it in a variable.