How does returning values from a function work?

后端 未结 8 1683
被撕碎了的回忆
被撕碎了的回忆 2021-01-05 12:16

I recently had a serious bug, where I forgot to return a value in a function. The problem was that even though nothing was returned it worked fine under Linux/Windows and on

8条回答
  •  半阙折子戏
    2021-01-05 12:44

    As Kerrek SB mentioned, your code has ventured into the realm of undefined behavior.

    Basically, your code is going to compile down to assembly. In assembly, there's no concept of a function requiring a return type, there's just an expectation. I'm the most comfortable with MIPS, so I shall use MIPS to illustrate.

    Assume you have the following code:

    int add(x, y)
    {
        return x + y;
    }
    

    This is going to be translated to something like:

    add:
        add $v0, $a0, $a1 #add $a0 and $a1 and store it in $v0
        jr $ra #jump back to where ever this code was jumped to from
    

    To add 5 and 4, the code would be called something like:

    addi $a0, $0, 5 # 5 is the first param
    addi $a1, $0, 4 # 4 is the second param
    jal add
    # $v0 now contains 9
    

    Note that unlike C, there's no explicit requirement that $v0 contain the return value, just an expectation. So, what happens if you don't actually push anything into $v0? Well, $v0 always has some value, so the value will be whatever it last was.

    Note: This post makes some simplifications. Also, you're computer is likely not running MIPS... But hopefully the example holds, and if you learned assembly at a university, MIPS might be what you know anyway.

提交回复
热议问题