Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is default return variable of function always allocated?

I'm interested in how default variable named the same as the function is implemented.

  • Is Sum always allocated even if I am not using it? (see case 1)
  • If I choose another variable (Total in CASE 3), is it used instead of Sum?

Are the following 3 equivalent cases also equivalent when compiled? Or is some superior to others?

' EQUIVALENT CASES

' CASE 1
Function Sum(a As Integer, b As Integer) As Integer
    Return a + b
End Function

' CASE 2
Function Sum(a As Integer, b As Integer) As Integer
    Sum = a + b
End Function

' CASE 3
Function Sum(a As Integer, b As Integer) As Integer
    Dim Total As Integer
    Total = a + b
    Return Total
End Function

As I read somewhere, functions compiling to less than 32 bytes are inserted inline. I wonder whether in some cases, I might end above or below the limit just because of the chosen notation.

like image 363
miroxlav Avatar asked Jan 21 '15 14:01

miroxlav


People also ask

What is the default return value of a function?

The default return value from a function is int. Unless explicitly specified the default return value by compiler would be integer value from function.

Do functions return None by default?

That default return value will always be None . If you don't supply an explicit return statement with an explicit return value, then Python will supply an implicit return statement using None as a return value. In the above example, add_one() adds 1 to x and stores the value in result but it doesn't return result .

Do functions need to return value everytime?

Some functions don't return a significant value, but others do. It's important to understand what their values are, how to use them in your code, and how to make functions return useful values.

What is the default return value of a function without a return statement in Python?

Python Function without return statement If the function doesn't have any return statement, then it returns None .


1 Answers

I renamed your functions to Sum1, Sum2, and Sum3, respectively and then ran them through LinqPad. Here is the generated IL:

Sum1:
IL_0000:  ldarg.1     
IL_0001:  ldarg.2     
IL_0002:  add.ovf     
IL_0003:  ret         

Sum2:
IL_0000:  ldarg.1     
IL_0001:  ldarg.2     
IL_0002:  add.ovf     
IL_0003:  stloc.0     // Sum2
IL_0004:  ldloc.0     // Sum2
IL_0005:  ret         

Sum3:
IL_0000:  ldarg.1     
IL_0001:  ldarg.2     
IL_0002:  add.ovf     
IL_0003:  stloc.1     // Total
IL_0004:  ldloc.1     // Total
IL_0005:  ret         

It appears that Sum2 and Sum3 result in the same IL. Sum1 appears to be more efficient since it puts the result of the operator directly onto the stack. The others must pull the result off the stack into the local variable and then push it back onto the stack!

like image 129
Chris Dunaway Avatar answered Nov 13 '22 00:11

Chris Dunaway