What is the purpose of the unary plus (+) operator in C?

前端 未结 8 2102
攒了一身酷
攒了一身酷 2020-11-28 05:58

In C, it\'s legal to write something like:

int foo = +4;

However, as far as I can tell, the unary plus (+) in +4

8条回答
  •  无人及你
    2020-11-28 06:39

    I found two things that unary + operator do is

    • integer promotion
    • turning lvalue into rvalue

    integer promotion example:

    #include 
    
    int main(void) {
    
        char ch;
        short sh;
        int i;
        long l;
    
        printf("%d %d %d %d\n",sizeof(ch),sizeof(sh),sizeof(i),sizeof(l));
        printf("%d %d %d %d\n",sizeof(+ch),sizeof(+sh),sizeof(+i),sizeof(+l));
        return 0;
    }
    

    Typical output (on 64-bit platform):

    1 2 4 8
    4 4 4 8
    

    turning lvalue into rvalue example:

    int i=0,j;
    
    j=(+i)++; // error lvalue required
    

提交回复
热议问题