Cognex Interview Question

++*f = ++*g; What will happen in the above code?

Interview Answers

Anonymous

Oct 13, 2017

Dearest Ludwig, Um... No. Did you actually get this compile error or are you speculating? Here is a real answer: Prefix and dereference operations have the same precedence and associate right-to-left. So, the contents of "g" are incremented before being set to the value of "f" which are also incremented. If we are talking ints, say *f=2 and *g=4, then dereference happens, values are incremented, then the incremented value of *g is assigned to *f. The prefix on the left hand side is overwritten by the assignment and *f=*g=5.

1

Anonymous

Aug 12, 2017

That causes compile error ("Lvalue required as left operand of assignment"). This is because statement ++*g is identical to ++(*g), which means we get value pointed by g, increment it, and assign it to something else. But the left statement ++*f is also rvalue (not lvalue), hence error. But: *f++ = *g++; or: ++f; *f = ++*g; or: *++f = ++*g; is valid.