Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I increase int i by more than one using the i++ syntax?

Tags:

c++

c

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...

like image 899
st12 Avatar asked Nov 26 '22 20:11

st12


1 Answers

"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.

like image 54
S.Lott Avatar answered Nov 29 '22 09:11

S.Lott