Answer in brief
In C11, auto explicitly declares an automatic block-local object. Ordinary local variables usually have the same storage duration without writing auto.
Declaration
auto int count = 0;
int other_count = 0; /* also automatic here */
Main properties
- Scope is normally the enclosing block, from the declaration onwards.
- The local object has no linkage.
- A new block execution has its own automatic object.
- An initialiser is applied when the declaration is reached. Without a suitable initialisation, an ordinary automatic object does not have a useful guaranteed starting value.
Example trace
Each call to show creates its automatic count and initialises it to zero. The increment makes it 1, so three separate calls print 1, 1 and 1. The value is not saved for the next call. A local static counter behaves differently because it refers to one lasting object.
Uses
Automatic variables are suitable for temporary calculations, counters and intermediate results that belong to one call. Recursive calls can each have their own automatic parameter and local values. This helps one call avoid overwriting another call’s ordinary locals.
Important points
Initialise before reading. Avoid returning the address of an ordinary automatic local object because its lifetime ends when its block execution ends. auto does not mean that the compiler should infer the type in the C11 examples used here; the keyword must be understood in the selected language version.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void show(void)
{
auto int count = 0;
++count;
printf("%d\n", count);
}
int main(void)
{
show(); show(); show();
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
1
1
1
Related exam questions
Related questions in the storage classes category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
- September/October 2021 · Q1(b) · 8 marks
If a variable has auto storage class by default, why was the auto keyword introduced in C? Explain.
Paper P01 · page 1 - July 2021 · Q2(c) · 5 marks
List and explain storage classes in C.
Paper P04 · page 1
View this category in the exam question bank →