当我使用 C++ 而不是 C 时,这一行编译:
gmtime(&(*(time_t *)alloca(sizeof(time_t)) = time(NULL)));//用alloca创建一个左值
我对这种差异感到惊讶。甚至没有针对 C++ 的警告。
当我指定 gcc -x c
时,消息是:
playground.cpp:25:8: error: lvalue required as unary '&' operand
gmtime(&(*(time_t *)alloca(sizeof(time_t)) = time(NULL)));
^
这里的&
不就是一个address-of操作符吗?为什么在 C 和 C++ 中不同?
虽然我可以在 C 中使用复合字面量,但是否仍然可以修改我的语法以使其在 C 和 C++ 中都能工作?
最佳答案
在 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.
在 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.
(早期版本的语言标准在每种情况下都指定了相同的内容)。
由于寻址运算符只能对左值进行操作,因此代码在 C++ 中是正确的,但在 C 中则不正确。
关于“是否可以修改我的语法以使其在 C 和 C++ 中都能工作?”这个问题。这不是一个理想的目标;这两种语言是不同的,你应该决定你在写什么。这与尝试坚持适用于 C 和 Java 的语法一样有意义。
按照其他人的建议,您可以这样写:
time_t t = time(NULL);
gmtime(&t);
它比你原来的存在代码有好处:
- 更简单,因此更易于理解和维护
- 不依赖于非标准的
alloca
函数 - 没有潜在的对齐违规
- 不再使用内存,而且可能使用更少
关于c++ - 编译为 C++ 但不是 C(错误 : lvalue required as unary '&' operand),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34523923/