Auto Storage Class in C (Keyword)
Auto Storage Class in C
Auto is default storage class for all variables declared inside a function or block. So, we rarely write auto of any keyword in C.
Auto variables are only accessible within the block or function in which they were declared (which defines their scope). In the parent block or function where the auto variable was declared, these can be accessed within nested blocks.
However, using the idea of pointers presented here, they can also be accessed outside of their intended use by referring to the precise position in memory where the variables are stored.
Auto storage class
- The automatic storage class includes variables defined within functions or blocks with the auto specifier.
- If no storage class is specified, all variables defined within a function or block are automatically stored under that class.
- The block in which they are defined is local to variables with automatic storage classes.
- On leaving the block where they are defined, variables are destroyed.
- Any garbage value is the default value for the variables in the automatic storage class.
- The default storage class is called auto.
Working of the Code
- In this code auto int i is defined at different stages with different scopes.
- Each time auto int i is defined, it’s value will be printed only in that particular scope only.
- First of all auto int i = 3 will be printed, then it’s scope will end.
- Then auto int i = 2 will be printed, and then it’s scope will end.
- At the end auto int i = 1 will be printed.
#include<stdio.h> int main() { auto int i = 1; { auto int i = 2; { auto int i = 3; { printf("%d ",i); } } printf("%d ",i); } printf("%d ",i); return 0; }
Output
3 2 1
Now we will write above code without using auto keyword
- Without using auto keyword still the output of the program will be same.
- First of all int i = 3 will be printed.
- Then int i = 2 will be printed.
- At the end int i = 1 will be printed.
#include<stdio.h> int main() { int i = 1; { int i = 2; { int i = 3; { printf("%d ",i); } } printf("%d ",i); } printf("%d ",i); return 0; }
Output
3 2 1
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment