Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

External/global variable in C

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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") ;
    }
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading