Compiles as C ++ but not C (error: lvalue required as a unary operand &

This line compiles when I use C ++, but not C:

gmtime(&(*(time_t *)alloca(sizeof(time_t)) = time(NULL))); //make an lvalue with alloca

I am surprised at this difference. In C ++ there is not even a warning.

When I specify gcc -xc , this message is:

 playground.cpp:25:8: error: lvalue required as unary '&' operand gmtime(&(*(time_t *)alloca(sizeof(time_t)) = time(NULL))); ^ 

Isn't & just an address operator here? Why is it different from C and C ++?

Although I can use compound literals in C, can I still change my syntax so that it works in both C and C ++?

+5
source share
1 answer

In C11 6.5.16 / 3:

The assignment operator stores the value in the object indicated by the left operand. The assignment expression has the value of the left operand after assignment , but not lvalue .

In C ++ 14 5.17 / 1:

Assignment operator (=) and compound assignment operators all groups from right to left. They all require a modifiable lvalue as their left operand and return an lvalue referring to the left operand.

(Earlier versions of language standards indicated the same thing in each case).

Since the operator address can only work with lvalue, the code is correct in C ++, but not in C.


Regarding the question "Is it possible to change my syntax so that it works both in C and C ++?". This is not a desired goal; the two languages ​​are different, and you must decide what you write. This has the same meaning as trying to stick with syntax that works in both C and Java.

As suggested by others, you can write:

 time_t t = time(NULL); gmtime(&t); 

which has advantages over your source code:

  • simpler, therefore easier to understand and maintain
  • independent of the non-standard alloca function
  • There is no potential misalignment.
  • uses more memory and possibly uses less
+8
source

Source: https://habr.com/ru/post/1239467/


All Articles