Jozef Tománek Jozef Tománek - 1 year ago 65
C Question

Basing a logical argument on status of initialization of variable

Say we defie num somewhere (local variable)

int num;

then, if initialized, say :

num = 420;

we do something, if not, we don't.

Is this possible in C99 / c overall? can't find it in the manual.

Answer Source

If you just write

num = 420;

and then try to depend your action on the fact if num has been initialized, then no, you cannot do that.
The reason is that C doesn't store the information, whether a variable has been initialized or not, anywhere at runtime. Only the compiler knows that at compile time.
Checking if num == 420 wouldn't work either. If it's an automatic variable and hasn't been initialized it's value is indeterminate and might very well be 420 without explicit initialization. Accessing that variable without initialization is undefined anyway.

What you could do is to depend the initialization on some condition, like this:

if (cond)
    num = 420;

Now, !cond is equivalent to "num has not been initialized." You can depend any further code on that condition cond, and it'll only execute if cond is true, which is equivalent to "num has been initialized with 420."

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download