1

Why does this code print out n-100?

    int hello(int n)
    {
        for(int i = 0; i < n-100; i++)
        {
        }
    }

    int main()
    {
            int h = hello(12);
        cout << hello(12) << " " << h << endl;
    }

Yet, both of these function return garbage (2665092 and 0 respectively)

    int hello1(int n)
    {
          for(int i = 0; i < 12; i++);
    }


    int hello2(int n)
    {
         (n - 100);
    }

I compiled this code using g++ in the cygwin environment.

Bill Trok
  • 147
  • 3
  • 1
    *"Why does this code print out n-100?"* It doesn't, I get `1 1`. :) – jrok Feb 10 '13 at 17:26
  • The return value is supposed to be stored somewhere, like in a register. If you don't set the return value, that register might contain something else, like a value you used recently. – Bo Persson Feb 10 '13 at 17:31
  • @BoPersson ahh thank you, that makes a whole lot of sense. – Bill Trok Feb 10 '13 at 17:43

1 Answers1

5

You are simply seeing the result of undefined behaviour.

Always compile with -Wall -Werror to prevent this kind of bug from creeping into your code.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680