简体   繁体   English

编译为C ++而不是C(错误:左值作为一元'和'操作数)

[英]Compiles as C++ but not C (error: lvalue required as unary '&' operand)

This line compiles when I use C++, but not C: 当我使用C ++时,这行编译,但不是C:

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

I'm surprised by this difference. 我对这种差异感到惊讶。 There is not even a warning for C++. 甚至没有C ++的警告。

When I specify gcc -xc , the message is: 当我指定gcc -xc ,消息是:

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

Isn't the & here just an address-of operator? 这不是&这里只是一个地址的运营商? Why is it different in C and C++? 为什么它在C和C ++中有所不同?

Although I can use compound literals in C, still is it possible to modify my syntax to make it work in both C & C++? 虽然我可以在C中使用复合文字,但仍然可以修改我的语法以使其在C&C ++中都有效吗?

In C11 6.5.16/3: 在C11 6.5.16 / 3中:

An assignment operator stores a value in the object designated by the left operand. 赋值运算符将值存储在左操作数指定的对象中。 An assignment expression has the value of the left operand after the assignment, but is not an lvalue . 赋值表达式在赋值后具有左操作数的值, 但不是左值

In C++14 5.17/1: 在C ++ 14 5.17 / 1中:

The assignment operator (=) and the compound assignment operators all group right-to-left. 赋值运算符(=)和复合赋值运算符都是从右到左分组。 All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand. 所有都需要一个可修改的左值作为左操作数, 并返回一个左值操作数的左值

(Earlier versions of the language standards in each case specified the same thing). (早期版本的语言标准在每种情况下指定相同的东西)。

Since the address-of operator can only operate on an lvalue, the code is correct in C++ but not in C. 由于address-of运算符只能在左值上运行,因此代码在C ++中是正确的,但在C中则不正确。


Regarding the question "Is it possible to modify my syntax to make it work in both C & C++?". 关于“是否可以修改我的语法以使其在C&C ++中都能正常工作?”的问题。 This is not a desirable goal; 这不是一个理想的目标; the two languages are different and you should decide what you're writing. 这两种语言是不同的,你应该决定你写的是什么。 This makes about as much sense as trying to stick to syntax that works in both C and Java. 这与尝试坚持在C和Java中都有效的语法一样有意义。

As suggested by others, you could write: 正如其他人所建议的,你可以写:

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

which has the benefits over your original code of being: 这比以前的原始代码有好处:

  • simpler, therefore easier to understand and maintain 更简单,因此更容易理解和维护
  • does not depend on non-standard alloca function 不依赖于非标准的alloca函数
  • does not have potential alignment violation 没有潜在的对齐违规
  • uses no more memory and perhaps uses less 不再使用内存,也许使用更少

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM