int fkt(int &i) { return i++; }
int main()
{
int i = 5;
printf("%d ", fkt(i));
printf("%d ", fkt(i));
printf("%d ", fkt(i));
}
prints '5 6 7 '. Say I want to print '5 7 9 ' like this, is it possible to do it in a similar way without a temporary variable in fkt()? (A temporary variable would marginally decrease efficiency, right?) I.e., something like
return i+=2
or
return i, i+=2;
which both first increases i and then return it, what is not what I need.
Thanks
EDIT: The main reason, I do it in a function and not outside is because fkt will be a function pointer. The original function will do something else with i. I just feel that using {int temp = i; i+=2; return temp;} does not seem as nice as {return i++;}.
I don't care about printf, this is just for illustration of the use of the result.
EDIT2: Wow, that appears to be more of a chat here than a traditional board :) Thanks for all the answers. My fkt is actually this. Depending on some condition, I will define get_it as either get_it_1, get_it_2, or get_it_4:
unsigned int (*get_it)(char*&);
unsigned int get_it_1(char* &s)
{return *((unsigned char*) s++);}
unsigned int get_it_2(char* &s)
{unsigned int tmp = *((unsigned short int*) s); s += 2; return tmp;}
unsigned int get_it_4(char* &s)
{unsigned int tmp = *((unsigned int*) s); s += 4; return tmp;}
For get_it_1, it is so simple... I'll try to give more background in the future...
"A temporary variable would marginally decrease efficiency, right?"
Wrong.
Have you measured it? Please be aware that ++
only has magical efficiency powers on a PDP-11. On most other processors it's just the same as +=1
. Please measure the two to see what the actual differences actually are.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With