How to check if a variable has been assigned a value?

Aug 6, 2012 at 5:11pm
I've been wondering how do check whether or not a variable has been assigned a value for a long time now. Would you want to make an 'if' statement to do so? I've tried things like if(a==...) and (a!=null) but now I'm starting to feel like a C++ noob(Which I am).

Please help

Bufflez
Aug 6, 2012 at 5:14pm
Unlike C# and some other languages, variables in C++ will always have some data contained in them. It's just that when you fail to initialize them yourself, that data is unpredictable garbage.

Therefore there is no way to check whether or not a variable has been assigned. Good practice is to just make sure they are always assigned as soon as you create them.
Aug 6, 2012 at 5:15pm
It's not possible to check that. You should always initialize your variables before using them.

If a is a pointer you can initialize it to null and check if a is not null by doing
if (a) or
if (a != 0) or
if (a != NULL) or
if (a != nullptr) (This only works in C++11.)
Last edited on Aug 6, 2012 at 5:18pm
Aug 6, 2012 at 5:27pm
Thanks, you guys! from now on I'll make sure to initialize my variables. it just makes too much sense.
Topic archived. No new replies allowed.