In the language C auto is a keyword for specifying a storage duration. When you create an auto variable it has an “automatic storage duration”. We call these objects “local variables”. In C, all variables in functions are local by default. That’s why the keyword auto is hardly ever used.
The two variables “count” and “count2” have automatic storage duration. In other words, they will exist until the program execution reaches the closing bracket of the block where they were defined. In this case they will exist until we reach the end of the function.
1 2 3 4 5 | void some_function() { auto int count = 0; int count2 = 0; } |
While we are on the subject, let’s take another look at “block lifetime” variable.
1 2 3 4 5 6 7 8 9 10 11 | int main() { auto int number = 5; { auto int number = 20; printf("inner number: %d", number); } printf("\n"); printf("outer number: %d", number); return 0; } |
This code(also available on Git Hub) works and the result is:
inner number: 20
outer number: 5
We create an integer variable “number”. Then we open a code block.
The inner number is defined within the block. Then we print the “number”
variable. When there is more than one variable available with the same
name, we will always access the inner-most. When the program prints the
value of that number it reaches the end of the block. At this moment all
automatic variables defined in this block “lose scope”. Then we print
the first number, which is still in scope.
Still, this all will behave the same way if we remove the auto keyword.
None.
Really, there is no reason to use the auto keyword in C. The only place where we can use it is when we create a variable within a function but… all variables created there are already auto.
For backward compatibility.
The predecessors of C used the auto to declare variables. Back in the days there was a lot of code that had to be ported to the new C language. Adding the keyword to the language was of help in that case.
Many programmers use compilers that can compile both C++ and C code, like for example Microsoft’s Visual Studio. The standard C++11 changed the meaning of the keyword “auto” for C++. Now it declares a variable that will get its type from its initialization.
For that reason if you try to use the C auto on a C++ compiler you could get a syntax error.
Related topics:
Previous keyword: C keywords |
Next keyword: break |