3

I have a function that takes a void pointer as argument. I would like to cast that pointer to a specific type (e.g. double) and then increment it. The code below does exactly what I want

function(void *out){
  double *temp = (double*) out;
  temp++;
  out = temp;

  /* do something with out here */
}

However if I put everything in one expression like

(double*)out++;

or

((double*)out)++;

the compilter doesn't like it. Is there a more elegant way to do this?

DayAndNight
  • 199
  • 1
  • 12
  • `(double*)out++;` should not work, anyway... – Sourav Ghosh May 04 '16 at 08:00
  • 5
    _the compilter doesn't like it_..please elaborate... – Sourav Ghosh May 04 '16 at 08:01
  • 1
    ((double*)out)++ gives "lvalue required as increment operand" – DayAndNight May 04 '16 at 08:06
  • 3
    The *compiler* doesn't like it? Heck, *I* don't like it! What would such code achieve? – Kerrek SB May 04 '16 at 08:13
  • @KerrekSB : I'm reading arrays of different types from a text file, thus I need to cast it and then move the pointer. E.g. *(double*)out = atof((char*) charpointerfromfile); out = ((double*)out)+1; – DayAndNight May 04 '16 at 08:18
  • @DayAndNight: Yes, sure, but your proposed code doesn't achieve (or express) that. So the compiler is right to reject it, if for no other reason that to alert you to the fact that you have misstated your intention. Casts don't *change* an existing value; rather, they compute a *new* value (of a different type) that is the result of the cast expression. – Kerrek SB May 04 '16 at 08:26
  • Yes, thats why I posted the code that does exaclty what I want and asked how this could be done better. The accepted answer does exactly that. Thanks for the clarification though. (btw, the statement in my comment above should have some more stars in it, but I dont know what the escape character in this comment function is) – DayAndNight May 04 '16 at 08:31
  • Solution: don't write code as obscure as possible, but as readable as possible. Your original code was already far superior to `((double*)out)++;`. Merging everything into one single line will not give you better performance. It often creates subtle bugs though. – Lundin May 04 '16 at 08:36

1 Answers1

4

The expression

((double*)out)++;

is problematic because it tries to increment the result of a cast, which is not an lvalue. However, it is perfectly fine to add 1 to the result of a cast, and assign it back to out:

out = ((double*)out)+1;
Community
  • 1
  • 1
Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399