1

I couldn't figure out how the program works so I ran it on the computer and got the output:

the sum of 5 to 4 is 10

I do not understand how nMax is passed into the sumInts function (empty parameters) during function call however the value of n is taken from the global variable. That's the only way it n could increment into 5 and sum into 10.

thanks in advance

#include <stdio.h>
#include <stdlib.h>

void sumInts();

int n=0;
int nMax = 0;
int sum = 0;

int main(int argc, char* argv[]) {
    if (argc<2) {
        printf("Usage: ex2 7 \n");
        exit(-1);
    }
    nMax = atoi(argv[1]);

    for (n=1;n<nMax;n++) {
        sumInts();
        printf("The sum from %d to %d is %d \n" , n , nMax, sum);
    }

    return 0;
}

void sumInts() {
    while (n<= nMax) {
    sum = sum+n;
    n++;
    }
}
user2736738
  • 30,591
  • 5
  • 42
  • 56
Brian Ho
  • 11
  • 2

2 Answers2

2

nMax isn't actually passed into sumInts at all - it's what is known as a global variable. A global variable is a variable that is defined outside any function, can be used inside any function, and retains its value between function calls. Since nMax is global, setting it in the main function changes its value in sumInts and causes the program to run as you see. This is considered somewhat bad style in general though, and should probably be avoided to prevent bugs.

Logan Hunter
  • 397
  • 4
  • 8
  • Thanks everyone. I think i understand now. I just want to cofirm that its because when i assign argument value into nMax in the int main function has changed the global value of nMax into 4. Please correct me if im wrong – Brian Ho Mar 03 '18 at 02:57
  • If my answer solved your problem, please feel free to accept it. – Logan Hunter Mar 06 '18 at 20:10
0

There's no parameter passing.

Besides, both while and for loops share the same global variables.

The for (n=1;n<nMax;n++) is useless since while loop makes n<nMax condition false after 1 call to sumInts (and the result is correct).

So a lot of redundant code here, and also using global variables (specially with names like n) will get you into trouble soon enough.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219