Does it return a valid code?

I found out that the following code is accepted by Visual C ++ 2008 and GCC 4.3 compilers:

void foo() { } void bar() { return foo(); } 

I am a little surprised that it compiles. Is this a language function or is it a bug in compilers? What do the C / C ++ standards say about this?

+49
c ++ c compiler-construction
Aug 01 '10 at 17:49
source share
4 answers

This is a C ++ language function

C ++ (ISO 14882: 2003) 6.6.3 / 3

The return statement with an expression of type "cv void" can only be used in functions with a return type of cv void; an expression is evaluated just before the function returns to the caller.

C (ISO 9899: 1999) 6.8.6.4/1

A return statement with an expression must not appear in a function; the return type is invalid.

+66
Aug 01 '10 at 17:52
source share

Yes, this is a valid code. This is necessary when you have template functions so that you can use a single code. For example,

 template<typename T, typename P> T f(int x, P y) { return g(x, y); } 

Now g can be overloaded to return void when the second argument is a specific type. If "return void" is invalid, the call to f will be interrupted.

+49
Aug 01 '10 at 17:53
source share

This is true and can be very useful, for example, to create cleaner code in situations where you want to do some error handling before returning:

 void ErrRet(int code, char* msg) { // code logging/handling error } void f() { if (...) return ErrRet(5, "Error Message !"); // code continue } 
+5
Dec 15 '14 at 23:33
source share

Really. I often use it for input validation macros:

 #define ASSERT_AND_RETURN_IF_NULL(p,r) if (!p) { assert(p && "#p must not be null"); return r; } bool func1(void* p) { ASSERT_AND_RETURN_IF_NULL(p, false); ... } void func2(void* p) { ASSERT_AND_RETURN_IF_NULL(p, void()); ... } 
+1
Oct 11 '15 at 15:06
source share



All Articles