开发者

C++ nil vs NULL

OK, I have some C++ code in a header that is declared like this:

void StreamOut(FxStream *stream,const FxChar *name = nil);

and I get: error:

'nil' was not declared in this scope

nil is a pascal thing, correct?

Should I be using NULL?

I thought they were both the same or at le开发者_如何学Goast Zero, no?


In C++ you need to use NULL, 0, or in some brand new compilers nullptr. The use of NULL vs. 0 can be a bit of a debate in some circles but IMHO, NULL is the more popular use over 0.


nil does not exist in standard C++. Use NULL instead.


Yes. It's NULL in C and C++, while it's nil in Objective-C.

Each language has its own identifier for no object. In C the standard library, NULL is a typedef of ((void *)0). In C++ the standard library, NULL is a typedef of 0 or 0L.

However IMHO, you should never use 0 in place of NULL, as it helps the readability of the code, just like having constant variables in your code: without using NULL, the value 0 is used for null pointers as well as base index value in loops as well as counts/sizes for empty lists, it makes it harder to know which one is which. Also, it's easier to grep for and such.


0 is the recommended and common style for C++


If you run a search through glibc you'll find this line of code:

#define NULL 0

It's just a standard way (not sure if it was published anywhere) of marking empty pointers. Variable value of 0 is still a value. Pointer pointing to 0 (0x0000... (it's decimal zero)) is actually pointing nowhere. It's just for readability.

int *var1, var2;
var1 = 0;
var2 = 0;

The above two assignments are not the same though they both look the same


just add at the beginning

#define null '\0'

or whatever you want instead of null and stick with what you prefer. The null concept in C++ is just related to a pointer pointing to nothing (0x0)..

Mind that every compiler may have its own definition of null, nil, NULL, whatever.. but in the end it is still 0.

Probably in the source you are looking at there is a

#define nil '\0'

somewhere in a header file..


I saw some comments on why not to use 0. Generally people don't like magic numbers, or numbers with meaning behind them. Give them a name. I would rather see ANSWER_TO_THE_ULTIMATE_QUESTION over 42 in code.

As for nil, I know Obj-C using nil as well. I would hate to think that someone went against the very popular convention (or at least what I remember) of NULL, which I thought was in a standard library header somewhere. I haven't done C++ in awhile though.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜