Why a warning of “control reaches end of non-void function” for the main function?

后端 未结 3 954
野性不改
野性不改 2021-02-18 17:25

I run the following C codes and got a warning: control reaches end of non-void function

int main(void) {}

Any suggestions?

相关标签:
3条回答
  • 2021-02-18 17:56

    The main function has a return-type of int, as indicated in

    int main(void)
    

    however your main function does not return anything, it closes after

    puts(strB);
    

    Add

    return 0;
    

    after that and it will work.

    0 讨论(0)
  • 2021-02-18 18:02

    Just put return 0 in your main(). Your function main returns an int (int main(void)) therefore you should add a return in the end of it.

    Control reaches the end of a non-void function

    Problem: I received the following warning:
    

    warning: control reaches end of non-void function

    Solution: This warning is similar to the warning described in Return with no value. If control reaches the end of a function and no return is encountered, GCC assumes a return with no return value. However, for this, the function requires a return value. At the end of the function, add a return statement that returns a suitable return value, even if control never reaches there.

    source

    Solution:

    int main(void)
    {
        my_strcpy(strB, strA);
        puts(strB);
        return 0;
    }
    
    0 讨论(0)
  • 2021-02-18 18:09

    As an alternative to the obvious solution of adding a return statement to main(), you can use a C99 compiler (“gcc -std=c99” if you are using GCC).

    In C99 it is legal for main() not to have a return statement, and then the final } implicitly returns 0.

    $ gcc -c -Wall t.c
    t.c: In function ‘main’:
    t.c:20: warning: control reaches end of non-void function
    $ gcc -c -Wall -std=c99 t.c
    $ 
    

    A note that purists would consider important: you should not fix the warning by declaring main() as returning type void.

    0 讨论(0)
提交回复
热议问题