postfix (prefix) increment, L-value and R-value (in C and C++)

后端 未结 2 1000
面向向阳花
面向向阳花 2021-01-03 04:13

I just learned the following facts:

  • The result of a prefix increment (++var_name) is an R-value in C (at least, I am sure that it is no

相关标签:
2条回答
  • 2021-01-03 04:57

    C and C++ are different languages. C++ has operator overloading and C does not. The ++ operators, whether prefix or postfix, are operators which can be overloaded in C++. C++ also has references and C does not.

    In C, ++i and i++ both yield a value which is not an lvalue. This is desirable, as otherwise you could run afoul with undefined behaviour by trying to modify the same scalar within the same sequence-point boundaries.

    Food for thought: In C, the comma operator also produces a value which is not an lvalue, so to "drop" lvalueness, you can do:

    (0, lvalue)
    
    0 讨论(0)
  • 2021-01-03 05:08

    It is true that

    • pre increment/decrement operator (++var or --var) yields an lvalue (i.e a modifiable object)

    • post increment/decrement operator (var++ or var--) yields an rvalue (i.e a temporary object).

    Consider following code with pre increment/decrement operator

    {
    
    int i = 0;
    
    int* pi = &(++i);
    
    }
    

    It´s OK because in fact its pseudo code is

    i = i+1; // pre increment i
    
    int* pi = &i; // then evaluate its address and assign it to pi 
    

    Now consider the same code but with post increment/decrement operator and the consequences if this invalid code is accepted by the compiler

    {
    
    int i = 0;
    
    int* pi = &(i++); // Not OK !! because it is a temporary variable
    
    }
    

    Its pseudo code would be

    int i = 0;
    
    int tmp = i; // compiler creates a temporary variable to save value of i
    
    int* pi = &tmp; // then would take the address of a temporary variable 
    
    i = i + 1; 
    
    0 讨论(0)
提交回复
热议问题