相对于一元算术运算符,C和C之间存在差异的原因是什么

在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&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...