Home > OS >  External/global variable in C
External/global variable in C

Time:05-12

I am learning about global variables in C using book C programming a modern approach.

Below is given an example from the book why using same global variable for multiple functions is bad idea. I don't understand why function print_all_rows executes function print_one_row only once.

Let's say I call first function print_one_row and then function print_all_rows. At the beginning of program i is set to 0 by default by compiler. Once program finishes execution of print_one_row function the value of i is 11.

Program enters into function print_all_rows, sets i to 1, calls function print_one_row and then increments i to 12 instead of 2.

Why is it incrementing i to 12 and not to 2 if I changed the value of i to 1?

int i;
void print_one_row(void)
{
    
    for (i = 1; i <= 10; i  )
        printf ("*" ) ;
}
void print_all_rows(void) {
    
    for (i = 1; i <= 10; i  ) {
        print_one_row();
        printf ("\n") ;
    }
}

CodePudding user response:

In print_all_rows, just before the first call to print_one_row, i has the value of 1.

Then print_one_row is called. When that function returns, i has the value of 11. Then the loop increment in print_all_rows is evaluated which increments i from 11 to 12, then the condition is evaluated which is false, then print_all_rows returns.

CodePudding user response:

Because i is glocal variable (common for both functions) and its value is 11 after first call of print_one_row. With this value (11) the second iteration of for loop in print_all_rows exits and there are no more calls of print_one_row.

  •  Tags:  
  • c
  • Related