Day#68 'C' Coding Challenge

Day#68 'C' Coding Challenge

What is the output of the below code?

#include <stdio.h> main() { int var; for(var=0; var<3; var++) { static int var_1 = 0; int var_2 = 0; var_1++; var_2++; printf("%d\n%d\n",var_1,var_2); } }

--------------------------------------------------

In the above program there are two variables var_1 and var_2 are declared inside a for loop, var_1 is static type and var_2 is auto type. With storage class static, the life of the variable is throughout the end of the program and for auto life of the variable is till the end of that particular block. So, when loop runs through 3 times, due to static word declaration, the previous value of the var_1 is held as is in between the loop execution and hence the var_1 is printed as 1,2,3. For var_2, as it is initialized to 0 every time, the value of var_2 shall be 1,1,1.

storage classes in c:

  • Storage class indicate the scope and lifespan of a variable. 
  • Storage class also indicates who can access a variable and from which location. 
  • There are 4 storage classes in C programming
  • Storage classes in C programming are:
    • Auto
    • extern
    • register
    • static

Post a Comment

0 Comments