I'm trying to write a function prototype, and define and call the function. The function is called distance and should return a float and accept two float parameters(rate and time).
Here's what I have, but I don't think its correct. Would appreciate any input!
At least with g++, it is definitely more efficient. I checked the assembly output for this program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
float dist1 (float a, float b) {
float ret;
ret = a * b;
return ret;
}
float dist2 (float a, float b) {
return (a * b);
}
int main() {
float x = 10;
float y = 50.34;
float z = dist1(x, y);
z = dist2(x, y);
return 0;
}
Here's the first function (with the added local variable):
I really don't know, actually. I'm not intimately familiar with assembly; all I can do is scan some simple code (like the above) and get the basic meaning.
Also, when one snippet is significantly shorter than the other, that's pretty significant hint. ;D
#include <iostream>
usingnamespace std;
// Function Prototype. This declares Distance to be a function that needs
// two float variables as arguments.
float Distance(float, float);
// Main function
int main()
{
float rate = 5; // Declare a first float variable
float time = 6; // And a second float variable
// This is the function call. The arguements can be ANY name so long as they
// the name of float variables.
float dist = Distance(rate, time);
cout << "Distance is " << dist << endl;
return 0;
}
// Function Definition. This function will return a float.
float Distance(float rate, float time)
{
float value = rate * time;
return value; // Return the value of the variable 'value'
}
ah, I think I get it. these two commands are necessary for the argument passing:
1 2
pushl %ebp
movl %esp, %ebp
and then you load a register with the first argument: flds 8(%ebp)
and multiply that register with the second argument: fmuls 12(%ebp)
In this case no temporary float object is created because the result is stored in a register! So I guess for standard types this is faster, because they can be stored directly in a register. And I suppose this means that for user defined types there is no difference. But would you like to check this too please? So we are sure about what happens.