0

Here is the code :

#include<iostream>
using namespace std;
int a, b;
int f(int c)
{
    int n = 1;
    for (int i = 0; i < c, i++;)
    {
        int a = n + i;                              
    }                                     
    return a;
}
void main()
{
    int i = 3;
    int b = f(i);          
    cout << a << b << i;
}

The output is 0,0,3

I understand the a = 0 because it is a global variable and defaults to 0, and i = 3, but I can't figure out how or why b = 0

samh30
  • 1
  • 3
  • 3
    Name your variables better and you will find out. You have two declarations of `a`, so your call to `f()` returns the global one. – Tas Mar 20 '18 at 02:50
  • 1
    `-Wall` reveals the bug as well: `weird.cpp:9:13: warning: unused variable ‘a’ [-Wunused-variable]` – Stephen Newell Mar 20 '18 at 02:51
  • you have two 'a' one global and one local to that 'for-loop' at the bottom of 'f' it returns the global 'a' that is 0 – nullqube Mar 20 '18 at 02:51
  • 2
    Your loop in `f` has a comma, shouldn't that be a semicolon? – Robert Mar 20 '18 at 02:52

3 Answers3

2

In your program, f() always returns 0. The a inside the for loop is a different a from the global variable (it "shadows" it). Therefore, local variable b in main() (which shadows global b) is initialized to 0 by the call to f().

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
1

Because in for loop of function f, a is a local varaible. Its scople is effective only in for loop. So return value is global a; So return 0;

PZY
  • 131
  • 1
  • 16
0

While others have already pointed out that you write to a local a in your loop, but return the global a, it's also worth nothing that even if you fix that, your loop will actually never enter it's body, because i < c, i++ evaluates to 0, which will be interpreted as false. (See What does the comma operator , do? .)

You need to fix your entire loop to this:

for (int i = 0; i < c; i++)
{
    a = n + i;                              
}
Max Vollmer
  • 8,412
  • 9
  • 28
  • 43