| by Arround The Web | No comments

Auto Keyword in C

The “auto” keyword in the C programming language is used to specify the storage duration of a variable. In other words, this keyword is used to declare the scope of a variable in C. The variables that are declared with the “auto” keyword in C have automatic storage duration. Such variables are known as local variables. However, an interesting fact is that all the variables in the C programming language are “local” by default. Therefore, technically, there is no need to use the “auto” keyword in C. Nevertheless, we will still discuss the working of the “auto” keyword in this article.

Auto Keyword in the C Programming Language

To use the auto keyword in the C programming language, you can take a look at the following example:

In this example, we declared an integer variable with the “auto” keyword and assigned to it the “2” value. Then, we displayed this value on the terminal. After that, we used the braces to define a new scope. Within these braces, we redefined the very same variable with a new value of “4”. We also printed this value on the terminal. Then, we printed the value of this variable yet again outside these braces.

After that, the following command is used to compile this code:

$ gcc auto.c –o auto

To execute this code, the following command is used:

$ ./auto

This program rendered a very interesting output which is shown in the following image. The scope of the variable “num” which is declared, initially lasted until the end of the “main()” function. Whereas the scope of its redefinition was only inside the braces. Because of this, the value of this variable before and after the braces remained “2”. While its value within the braces was “4”.

Achieving the Same Functionality Without the Auto Keyword in C

Now, we will see how the very same functionality can be achieved without using the “auto” keyword. For that, we use the same C script as shown in the previous example. But this time, we simply remove the “auto” keyword from everywhere. This is shown in the following image:

The output of this program is shown in the following image. You can clearly witness that the output remained exactly the same even without using the “auto” keyword which confirms that there is as such no need of using the “auto” keyword in the C programming language.

Conclusion

This article is directed towards the usage of the “auto” keyword in the C programming language. However, we also witnessed how the same functionality can be achieved without even using this keyword in C. Therefore, it totally depends on you whether you want to use or skip this keyword.

Share Button

Source: linuxhint.com

Leave a Reply