In C++, is "return;" the same thing as "return NULL;"?
is
return;
the same asreturn NULL;
in C++?
No.
return
is used to "break" out from a function that has no return value, i.e. a return type of void
.
return NULL
returns the value NULL
, and the return type of the function it's found in must be compatible with NULL
.
I understand that in C++,
return NULL;
is the same asreturn 0;
in the context of pointers.
Sort of. NULL
may not be equivalent to 0
, but it will at least convert to something that is.
Obviously for integers, this is not the case as NULL cannot be added, subtracted, etc.
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 to 0
or 0UL
.
Some modern compilers will at least warn you if it was actually NULL
you wrote, though.
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.
No. And I disagree with this advice. Though I can see where it's coming from, since NULL
's exact definition varies across implementations, using NULL
will make it much easier to replace with nullptr
when you switch to C++11, and if nothing else is self-documenting.
return
with no expression works only if your function is declared void
, in a constructor, or in a destructor. If you try to return nothing from a function that returns an int
, a double
, etc., your program will not compile:
error: return-statement with no value, in function returning ‘int’
According to §6.6.3/2 of C++11:
A return statement with neither an expression nor a braced-init-list can be used only in functions that do not return a value, that is, a function with the return type void, a constructor (12.1), or a destructor (12.4).
(thanks sftrabbit for the excellent comment).