开发者

Is NULL the same as False in C++

开发者 https://www.devze.com 2022-12-16 18:35 出处:网络
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++ s

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.


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


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++ */


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.


NULL on gcc on some platforms (Mac) is much more complicated than that. It tries to start using the nullptr thingy from next cxx rev. Even so it should still evaluate to false in a boolean context

0

精彩评论

暂无评论...
验证码 换一张
取 消