c++ - 编译为 C++ 但不是 C(错误 : lvalue required as unary '&' operand)

标签 c++ c compiler-errors lvalue rvalue

当我使用 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/

相关文章:

c++ - "multiple definition of value"在 g++ 而非 gcc 中编译具有未初始化全局的 C 程序时

C编译错误: Undefined symbols for architecture x86_64: "_stringAdd"

java - 在哪里抛出异常句柄?

c++ - 为什么 'this' 指针不能用在构造函数初始值设定项列表中?

c++ - 尝试在 Mac OS X 上编译基于 linux 的应用程序

c - 移入一位(此位应为“1”)

c - 双重类型转换与双重功能

c++ - 如何使用 nlohmann::json 将 json 对象转换为 map ?

c++ - 软件版本中添加新参数时如何处理 "switch/case"

c - retarget.c 是如何工作的