Why “not all control paths return a value” is warning and not an error?

后端 未结 7 1813
花落未央
花落未央 2020-12-02 01:48

I was trying to answer this question. As suggested by the accepted answer, the problem with that code is that not all control paths are returning a value. I tried this code

7条回答
  •  再見小時候
    2020-12-02 02:20

    I would guess it is only a warning because the compiler cannot always be 100% sure it is possible to not hit a return.

    i.e. if you had:

    
    -= source1.c =-
    int func()
    {
        if(doSomething())
        {
           return 0;
        }
    }
    
    -= source2.c =-
    int doSomething()
    {
        return 1;
    }
    

    The compiler in this case might not be able to know it will always hit the return, but you do. Of course this is terrible programming practice to rely on knowing how external code works.

    As for what will actually be returned it depends on the platform. On x86 ABIs EAX is used for the return value (up to 32bits) so it will return what ever was placed in that register (which could be a return from something else, a temporary value or total garbage).

提交回复
热议问题