Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for the existent difference between C and C++ relative to the unary arithmetic operator +

In C the unary plus operator is called unary arithmetic operator and may not be applied to pointers (the C Standard, 6.5.3.3 Unary arithmetic operators).

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

Thus this program will not compile

#include <stdio.h>

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

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

    return 0;
}

However in C++ the unary plus operator may be applied to pointers (the C++ Standard, 5.3.1 Unary operators)

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.

And this program compiles successfully.

#include <iostream>

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

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

    return 0;
}

What is the reason for maintaining this difference between C and C++?


The question arose when I was answering the question Why size of int pointer is different of size of int array?. I was going to show how to convert an array to a pointer in the sizeof operator.

At first I wanted to write

sizeof( +array )

However this expression is invalid in C. So I had to write

sizeof( array + 0 )

and I found that there is such a difference between C and C++.:)

like image 211
Vlad from Moscow Avatar asked Jan 18 '17 09:01

Vlad from Moscow


1 Answers

Different languages may attach different semantics to the same syntax.

C and C++ are different languages with a common ancestor. C++ semantics look deceptively similar but are subtly different for some parts of the common syntax. Another curious case is this:

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");
}

The reason for C++ to have extended the C syntax in the case of unary + might be to allow for some extended numeric types to be implemented as pointers, or simply for reasons of symmetry.

As Jaa-c mentions in a comment, +p is a computed expression whereas p is a reference to p. You provided another example where + can be used to force expression context. The question is why did the original authors of the C language disallow unary + on non numeric types? Maybe a side effect of the original implementation of pcc.

Note that in Javascript, the unary + operator can be applied to non number types and operates as a conversion to number.

like image 146
chqrlie Avatar answered Nov 12 '22 16:11

chqrlie