Why does the following code run?
#include <iostream>
class A {
int num;
public:
void foo(){ num=5; std::cout<< "num="; std::cout<<num;}
};
int main() {
A* a;
a->foo();
return 0;
}
The output is
num=5
I compile this using gcc and I get only the following compiler warning at line 10:
(warning: 'a' is used uninitialized in this function)
But as per my understanding, shouldn't this code not run at all? And how come it's assigning the value 5 to num when num doesn't exist because no object of type A has been created yet?
The code produces undefined behavior, because it attempts to dereference an uninitialized pointer. Undefined behavior is unpredictable and follows no logic whatsoever. For this reason, any questions about why your code does something or doesn't do something make no sense.
You are asking why it runs? It doesn't run. It produces undefined behavior.
You are asking how it is assigning 5 to a non-existing member? It doesn't assign anything to anything. It produces undefined behavior.
You are saying the output is 5
? Wrong. The output is not 5
. There's no meaningful output. The code produces undefined behavior. Just because it somehow happened to print 5
in your experiment means absolutely nothing and has no meaningful explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With