C void function with return value

前端 未结 2 1522
一整个雨季
一整个雨季 2020-12-19 10:23

As far as I know, return statement in void function will throw an error.

But in the below program that is not the case.

Here the displayed output

2条回答
  •  眼角桃花
    2020-12-19 11:14

    A return statement with no expression:

    void func(void) {
        return;
    }
    

    is perfectly legal in a void function. The legality of a return statement with an expression depends on the version of the C language you're using.

    The 1990 C standard says:

    A return statement with an expression shall not appear in a function whose return type is void.

    The 1999 and 2011 editions of the standard both say:

    A return statement with an expression shall not appear in a function whose return type is void. A return statement without an expression shall only appear in a function whose return type is void.

    This is a constraint, meaning that a compiler must issue a diagnostic (possibly a non-fatal warning) for any program that violates it.

    C90 permitted a return statement with no expression in a non-void function for historical reasons. Pre-ANSI C did not have the void keyword, so there was no way to define a function that didn't return a value. Programmers would omit the return type (which would default to int) and simply ignore it. The C90 rule allowed such old code to compile without error. You could still fail to return a value from a non-void function; the program's behavior is undefined if a caller attempts to use the (nonexistent) result. The 1999 standard tightened up the rules a bit.

    Another problem with your program is that you call fun before its declaration is visible. Under C99 and later rules, this is illegal (though a compiler might merely warn about it). Under C90 rules, this is legal, but the compiler will assume that the function returns int. Your program's behavior is undefined, but your void function fun might happen to behave as if it returned a value, and a call to it might happen to behave as if it used that value.

    C compilers tend to be fairly lax about some errors, so that old code (sometimes written before the first actual standard was published) will not be rejected. But your compiler should have at least warned you about the return statement, and probably about the invalid call. You should pay close attention to compiler warnings; they should be treated almost the same way as fatal errors. And you should use options to increase the number of things your compiler warns you about. If you're using gcc, use -std=c90, -std=c99, or -std=c11, along with -pedantic to enforce standard conformance. You can add -Wall-Wextra` to enable more warnings.

提交回复
热议问题