Home > database >  Is an undefined pointer variable NULL?
Is an undefined pointer variable NULL?

Time:01-05

The same code is giving me two different outputs when I run it in two different places. This is the code;

#include <iostream>
using namespace std;
struct test {
    int val;
};
int main() {
    test* a;
    cout << (a == NULL) << endl;
}

I get either 1 as the output:

enter image description here

or 0:

enter image description here

So, does an undefined pointer variable equals to NULL or not? What could be the reason for this variance?

CodePudding user response:

Without being explicitly initialized, it would only be initialized to NULL or nullptr if declared at file level ("globally") or with static.

Otherwise it is undefined. It might be NULL or it might be any other value. You are assuming it will be NULL, so the most dangerous thing that can happen is it coincidentally being NULL in any tests you run, as that will not check your assumption.

These pointer variables are initialized to NULL.

int *p;

int main() {
    // ...
}
int main() {
    static int *p;

    // ...
}

CodePudding user response:

First of all it is undefined. But usually if you run it in visual studio or similar platforms, in debug mode the compiler might initialize it to null terminated pointer, but in release mode it is just "garbage" which will return 0 from the "==" comparison. Hope this helps!

  • Related