someone please tell me which one of the following is more fast and why ??
int add(int a, int b){
return a+b;
}
OR
void add(int a, int *b){
*b = a+(*b);
}
someone please tell me which one of the following is more fast and why ??
int add(int a, int b){
return a+b;
}
OR
void add(int a, int *b){
*b = a+(*b);
}
Chances are functions are inlined and both result in the same generated code.
You should not try to guess which one is faster by looking at code, but profile the options under consideration to see whether one is faster than the other, andwhether it really makes a difference. Now concerning your example, I think returning by value is no problem at all, since most compilers these days perform return value and named return value optimzation, which are forms of copy elision. On top of that, C++11 introduces move semantics, which means that, where applicable, data is "moved" from a temporary to a target. So in fact, it may be faster to return by value, since you do not have to check the inputs.
For a related discussion on passing by value, see here, and for a related question, see here.
It is very unlikely that returning a value is slower than saving it as values are normally returned in registers (typically the accumulator if the CPU has one and the return value will fit).