Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is NULL the same as False in C++

Tags:

c++

In C++ (gcc,VS) is NULL considered the same as False. Or more importantly if in a logical statement what does NULL evaluate to. There were a number of other questions but none for C++ specifically.

For some reason looping with a NULL control for(;;) just freezes up the program indicating that there is something other than a NULL placed between the ;;. Note this code is something our professor believes to contain NULL values.

like image 960
Roo Avatar asked Jan 13 '10 01:01

Roo


3 Answers

I believe NULL is generally defined to be 0, which coincidentally evaluates to false when used as a boolean expression.

like image 124
Mike Daniels Avatar answered Oct 21 '22 05:10

Mike Daniels


In C++, NULL is #defined to 0 (and thus evaluates to false). In C, it is a void*, which also evaluates to false, but its type is not a numeric type. In the standard library (at least on GCC):

#ifndef __cplusplus
#define NULL ((void *)0)
#else   /* C++ */
#define NULL 0
#endif  /* C++ */
like image 31
Barry Wark Avatar answered Oct 21 '22 05:10

Barry Wark


It seems that you're considering the following code:

for (;;) { }

That will loop forever because the condition term is empty. You might be tempted to refer to that as the null condition to indicate that there is no condition present, but as you and everyone else who has read your question can attest, it's a confusing phrase to use because it does not mean the same as this:

for ( ; NULL; ) { }

The above won't loop at all. It uses the macro NULL, which is equivalent to the integer constant zero, and zero in a Boolean context is treated as false. That's not "the null condition" because there is a condition there — a condition that is always false.

If you got this from your professor, and he is teaching a class in C++, then I suspect you misunderstood him, because this isn't something I'd expect a professor to get wrong, so go ask him to fill in the hole in your notes. If he's not a C++ professor, then maybe he simply tried to use a C++ example to illustrate some other topic. You might wish to send him a note about it so that he can clarify and present some different example in future lectures.

like image 32
Rob Kennedy Avatar answered Oct 21 '22 05:10

Rob Kennedy