Int q not defined code still working

Can someone help me understand how is this program working when int is not even defined.
In the first iteration x = 0, so 0 will be printed because it is less than 3. In the next iteration x = x + foo() meaning x = 0 + q + 1. Therefore, in this second iteration it will checked q+1 < 3 but we don't know what is q then how will second iteration will be done?

#include <stdio.h>

int foo (int q) {
    int x = 1;
    return (q + x);
}
int main (){
   int x = 0;
   while (x < 3) {
  	printf ("%i ", x);
      x = x + foo(x);
    }
}

I typed this above code in the compiler and I was able to get 0 1. I don't know understand how?

There it is.

It might be easier to understand if you didn't reuse variable names like 'x'

1 Like
1a 
x = 0
print x = 0
x(of main) = x + foo(x(of main))  __  
inside foo   x(of foo) = 1  q(of foo) = 0  then q + x = 1

return 1  
then x(of main) +foo(x)  = 0 + 1 = 1

2a
x  = 1
print 1
x(of main) = x + foo(x(of main)) __   
inside foo  x(of foo) = 1  q(of foo) = 1  then q + x = 2

return 2  
then x(of main) = 2 +foo(x)  = 2 + 1 = 3

exit while

Read about variable scope

here it is type which is integer but what is the value of int q = ?

The value of q is whatever value you provided as the argument to the function when you called it.

Thanks, but I still habe problem understand which line is executing after a certain line of code. I am newbie. If we change the variable to a in the foo and b in the main probably then it might make sense to make. Can you explain by considering a and b as variable?

Have you read about variable scope and functions with parameters passed by value?

To be less confused don’t use the same variable names if they are different variables

#include <stdio.h>

int foo (int parameter) {
    int localFooVariable = 1;
    return (parameter + localFooVariable);
}
int main (){
   int mainX = 0;
   while (mainX < 3) {
  	printf ("%i ", mainX);
      mainX = mainX + foo(mainX);
    }
}
1 Like

I had some idea of local and global variable in python but in this particular code I was confuse with the same name of two variables and also because I didn't know how is exactly the code executes either line by line as in Python or other way around.

I am curious about what you mean by the "other way around".

Most languages can be read as executing code line by line…

a7

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.