Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can return keyword be omitted in a return statement?

Tags:

c++

I recently come across the below piece of code in this Apache Axis tutorial example.

int main()
{
    int status = AXIS2_SUCCESS;

    axutil_env_t *env = NULL;
    axutil_allocator_t *allocator = NULL;
    env = create_environment();

    status = build_and_serialize_om(env);

    (status == AXIS2_FAILURE)
    {
        printf(" build AXIOM failed");
    }

    axutil_env_free(env);

     0;
}

What i don't understand is the 0; at the end.
Is that return statement without the return keyword?

I tried the below piece of code to test this in Visual Studio.

int main()
{
    0; // in the second run, replaced 0 with 28
}

Both programmes ran without any problems. But echo %ERRORLEVEL% at windows command line returned 0 for both.

But the below piece of code

int add()
{
    0;
}

causes

Error 1 error C4716: 'add' : must return a value

I understand that return value 0 is implicitly added for the main().

I don't have a problem including the return keyword at all, but I am porting the Axis2/C Library to a C++ project. And there are many instances where I encountered 0;

Why is the above syntax causing this undefined behavior?

like image 572
sjsam Avatar asked Dec 19 '22 22:12

sjsam


2 Answers

In C++ return can be omitted only in main() , in functions that return void, and in constructors and destructors. In the former case main() returns automatically 0. In your case the statement 0; is a syntactically correct statement, evaluated as a no-op, so the compiler is basically ignoring it.

like image 74
vsoftco Avatar answered Dec 24 '22 01:12

vsoftco


Where did you find that code? It seems like it's corrupted, perhaps due to formatting for showing it on a web page or something...?

The original code (from https://github.com/bnoordhuis/axis2-c/blob/master/axiom/test/util/axiom_util_test.c) is:

int main()
{
    int status = AXIS2_SUCCESS;
    axutil_env_t *env = NULL;
    status = build_and_serialize_om(env);

    if(status == AXIS2_FAILURE)
    {
        printf(" build AXIOM failed");
    }

    axutil_env_free(env);
    return 0;
}
like image 39
PkP Avatar answered Dec 24 '22 01:12

PkP