c++ - C和C++相对于一元算术运算符存在差异的原因是什么 +

标签 c++ c pointers unary-operator

在 C 中,一元加号运算符称为一元算术运算符,可能不适用于指针(C 标准,6.5.3.3 一元算术运算符)。

1 The operand of the unary + or - operator shall have arithmetic type; of the ~ operator, integer type; of the ! operator, scalar type.

因此这个程序不会编译

#include <stdio.h>

int main(void) 
{
    int a = 10;
    int *pa = &a;

    printf( "%d\n", *+pa );

    return 0;
}

但是在 C++ 中,一元加运算符可以应用于指针(C++ 标准,5.3.1 一元运算符)

7 The operand of the unary + operator shall have arithmetic, unscoped enumeration, or pointer type and the result is the value of the argument. Integral promotion is performed on integral or enumeration operands. The type of the result is the type of the promoted operand.

并且这个程序编译成功。

#include <iostream>

int main() 
{
    int a = 10;
    int *pa = &a;

    std::cout << *+pa << std::endl;

    return 0;
}

维持 C 和 C++ 之间这种差异的原因是什么?


我在回答Why size of int pointer is different of size of int array?的问题时出现了这个问题.我打算展示如何在 sizeof 运算符中将数组转换为指针。

一开始我想写

sizeof( +array )

但是这个表达式在C中是无效的。所以我不得不写

sizeof( array + 0 )

而且我发现 C 和 C++ 之间存在这样的差异。:)

最佳答案

不同的语言可能会将不同的语义附加到相同的语法。

C 和 C++ 是具有共同祖先的不同语言。 C++ 语义看似相似,但在通用语法的某些部分却略有不同。另一个奇怪的案例是:

if (sizeof(char) == sizeof(int)) {
    printf("Hello embedded world\n");
} else {
    if (sizeof('a') == sizeof(char))
        printf("This is C++ code\n");
    if (sizeof('a') == sizeof(int))
        printf("This is C code\n");
}

C++ 在一元 + 的情况下扩展 C 语法的原因可能是允许将一些扩展的数字类型实现为指针,或者仅仅是出于对称的原因。

正如 Jaa-c 在评论中提到的,+p 是一个计算表达式,而 p 是对 p 的引用。您提供了另一个示例,其中 + 可用于强制表达式上下文。问题是为什么 C 语言的原作者不允许在非数字类型上使用一元 +?可能是 pcc 原始实现的副作用。

请注意,在 Javascript 中,一元运算符 + 可以应用于非数字类型,并作为数字的转换。

关于c++ - C和C++相对于一元算术运算符存在差异的原因是什么 +,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41716138/

相关文章:

c++ - 程序在 Ideone 上正确执行,但在 Xcode 中不正确

c++ - 使用 C++ 从 6 个字节或更多字节生成一个整数

c - 结果似乎是 0.00001 而不是我分配的值。为什么?

java - 通过套接字发送数据(Java 到 C)

c - 使用链表函数的内存范围

c++ - 如何在 char 数组中插入值?

c++ - C++ 中的垃圾回收/析构函数

c++ - 最有效的 const char* 比较不区分大小写

python - C++ DLL 返回从 Python 调用的指针

c - 我如何初始化指针类型结构元素