As in all programming languages, C uses variables. The variables can contain integers, reals, text .... Unlike constants, the content of variables can change during the execution of a program:
C is a typed language, that is to say that each variable is defined for a given type (integer, real, text...):
Here is an example of Python code that creates a variable named A
before displaying its value.
No type is declared where creating the variable:
# A is not declared before its first use
A = 5
# Display the value of A
print (A)
Let's now consider the same example in C. We notice here that the type of the variable (int
)
is specified at the time of its declaration:
// Declaration of the variable A and its type (int = integer)
int A = 5;
// Display the value of A
printf("%d\n", A);
Specifying the type of variables may seem restrictive for the developer. But it has the has the advantage of minimizing memory allocation and maximizing performance. The vast majority of critical industrial systems, embedded or real-time systems are programmed in C.
In C, there are 4 classes of variable types:
int
) which are used to store integer numbers : 0, 1, 25, -1024 ...float
) which are used to store real numbers : 0.2 , 15.5, -3.1415 ...char
) which are used to store alpha-numeric single characters : A, B, C ... Z, 0, 1, 2 ...9, ?, /, %, # ...char*
) which are used to store text: This is an informative message.In C, there is a precise vocabulary for the use of variables. To be sure to be understood, make sure you are familiar with :
The declaration of a variable corresponds to the line where the type is associated with the variable:
// Declare a variable with its type
int A;
The assignment of a variable is the line where the content of the variable is specified:
Assignment of variable A
A = 5;
It is common to perform the declaration and assignment in a single line:
int A = 5;
There are some restrictions on the naming of variables:
a to z and A to Z
).0 to 9
)._
).main
, return
, int
...).pressure_sensor
, screen_width
, nb_players
... ).Here are some examples of variables names that are syntactically correct:
int a;
int Z;
int Stuff;
int _duMP;
int Stuff_49;
Complete the following C code with:
Var
with type (int
) ;#include <stdio.h>
int main(void) {
// Declaration of an integer variable named var
// COMPLETE HERE
// Assignment of 128 to var
// COMPLETE HERE
// Display the content of var
printf ("The value of the variable is %d\n", Var);
return 0;
}
Modify the previous program so that the declaration and the assignment are done on the same line. on the same line.
What are the variable types in C?
**Which type is used to define integers?
Which type is used to define numbers with a decimal point?
What is the declaration of a variable?
Which variable names are correct?