Users Online

· Guests Online: 92

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Articles Hierarchy

C auto

C auto

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.


First code example

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;
}

Block visibility with auto

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.

Practical usage

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.

Why the C auto exists?

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.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 1.08 seconds
10,823,837 unique visits