-4

I have this code:

#include <iostream>

using namespace std;


void funcA()
{
    int a = 4;
}

void funcB()
{
    int b;
    cout << b;
}

int main()
{
    funcA();
    funcB();

    cout << endl;

    return 0;
}

If I compile it without optimization: g++ -o run file.cpp I am receiving as result : 4

If I compile it with : g++ -O3 -o run file.cpp I am receiving as result : 0

Now, I would expect in both cases

1) Return nothing from funcA since we are just calling it and in funcA we are just assigning a value to a variable ( don't return anything ).

2) Return a warning from compiler regarding funcB since we are not initializing b value.

I found this answer better (more detail).

Community
  • 1
  • 1
George
  • 5,808
  • 15
  • 83
  • 160
  • 3
    This is undefined behavior. What you get is what you get because undefined reason – NathanOliver Oct 31 '16 at 19:16
  • 4
    Well, undefined behavior is undefined and arguing about it is thus fairly useless. And if you want warnings, enable warnings. – Baum mit Augen Oct 31 '16 at 19:16
  • 2
    *Now, I would expect in both cases ...* -- Nope, undefined behavior doesn't work that way where you "expect" things to occur. – PaulMcKenzie Oct 31 '16 at 19:22
  • Thanks for the answers.I can see now what the problem is.(I can't understand though the downvotes because searching for an issue like this is difficult (Undefined, unspecified and implementation-defined behavior )compare this to my title. – George Oct 31 '16 at 20:46

2 Answers2

3

To get useful warnings, you have to ask for them. Run gcc with the -Wall -Wextra options and be amazed.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121
1

In C++ the compiler (without warning flags) won't warn you if you don't initialize a value.

If you initialize a variable what you actually do is allocating x bytes of data (in this case most likely 4). So even if you don't initialize it, there is 'something'.

In this case it probably reuses the chunk of memory previously taken by a, that is why you see 4 on the output.

If you run g++ with -03 flag (the biggest optimization) all values are initialized to 0. That is why you see 0 on the output.

SlowerPhoton
  • 888
  • 1
  • 7
  • 17
  • 1
    *"If you run g++ with -03 flag (the biggest optimization) all values are initialized to 0. That is why you see 0 on the output."* That's not true. – Baum mit Augen Oct 31 '16 at 19:25
  • Yes, you are right, g++ doesn't have a flag to set unitialized values to 0. – SlowerPhoton Oct 31 '16 at 19:33
  • 1
    With optimizations set high, the compiler may not emit code for funcA since there are no executable statements. And seeing that funcA serves no purpose, the compiler or linker may eliminate it. – Thomas Matthews Oct 31 '16 at 19:42