my question is return;
the same as return NULL;
in C++?
I understand that in C++, return NULL;
is the same as return 0;
in the context of pointers. Obviously for integers, this is not the case as NULL cannot be added, subtracted, etc. And that it is encouraged by some to use 0 instead of NULL for pointers because it is more convenient for portability. I'm curious if this is another instance where an equivalence occurs.
I suspect that they are equivalent because return;
is saying return 'nothing' and NULL is 'nothing.' However, if someone can either confirm or deny this (with explanation, of course), I would be very grateful!
It works like a void function, where the return will simply exit the function and return nothing at all. This has been asked before.
There is a difference in the resulting machine code:
return
will just put the instruction pointer back to where the caller came from.return 0
orreturn NULL
will put0
on the stack, and then put the instruction pointer back to where the caller came from. (In C,NULL
is usually mapped to0
, although that can (may?) differ in different implementations. In C++,NULL
is not supposed to be used).return
with no expression works only if your function is declaredvoid
, in a constructor, or in a destructor. If you try to return nothing from a function that returns anint
, adouble
, etc., your program will not compile:According to §6.6.3/2 of C++11:
(thanks sftrabbit for the excellent comment).
No.
return
is used to "break" out from a function that has no return value, i.e. a return type ofvoid
.return NULL
returns the valueNULL
, and the return type of the function it's found in must be compatible withNULL
.Sort of.
NULL
may not be equivalent to0
, but it will at least convert to something that is.You can perform addition and subtraction to pointers just fine. However,
NULL
must have integral type (4.10/1 and 18.1/4 in C++03) anyway so it's moot.NULL
may very well be a macro that expands to0
or0UL
.Some modern compilers will at least warn you if it was actually
NULL
you wrote, though.No. And I disagree with this advice. Though I can see where it's coming from, since
NULL
's exact definition varies across implementations, usingNULL
will make it much easier to replace withnullptr
when you switch to C++11, and if nothing else is self-documenting.return
,return 0
andreturn NULL
are not the same.return
is only valid with functions returningvoid
, e.g.:return 0
is for functions returning someint
type, e.g.:although it works with floating point types as well:
return NULL
is for functions returning somepointer
type, e.g.: