retagged by
884 views
1 votes
1 votes
#include<stdio.h>
void print1(void){
static int x=10;
x+=5;
printf("%d",x);
}
void print2(void){
static int x;
x=10;
x+=5;
printf("%d",x);
}
int main(){
print1();
print1();
print2();
print2();
getch();
return 0;
}

please let me know how print1 and print2 is working?
retagged by

1 Answer

1 votes
1 votes

Output: 15 20 15 15

Few things you should note here

  • Static variable retain their value even after they are out of scope
  • Initialization of static variable is done only once

Most of you already are knowing this.

void print1(void){
static int x=10; // x is declared as well as initialized , this statement will be executed only once
x+=5;
printf("%d",x);
}

print1() 1 st call

void print1(void){
static int x=10; // x=10
x+=5; // x=15
printf("%d",x); // prints 15
}

print1 2nd call 

void print1(void){

static int x=10; // not be executed 

// x value is 15 as static variable value is retained

x+=5; // x=20

printf("%d",x); // prints 15

}

Now print2()

void print2(void){
static int x; // x is declared and initialized to 0, this will be executed only once
x=10; // this is assignemnt of value to x and will be executed each time print2() is called
x+=5;
printf("%d",x);
}

print2() first call

void print2(void){
static int x; // x=0
x=10; // x=10
x+=5; // x=15
printf("%d",x); // prints 15
}

print2() 2nd call

void print2(void){

static int x; // not be executed

x=10; // x=10

x+=5; // x=15

printf("%d",x); // prints 15
}
edited by

Related questions

1 votes
1 votes
1 answer
3