precedence and associativity reg

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jeyshree
    New Member
    • Jul 2010
    • 75

    precedence and associativity reg

    hai,
    when i saw the below expression i faced a problem.
    int a=5,b;
    b=+++a;
    after this b has a value of 6.
    wheareas
    int a=5,b;
    b=---a;
    this results in l value error.whats happening?
    moreover the statement
    int a=5,b=7,c;
    c=a+++b;
    after this expression c has a value of 12,a has a value of 6,b has value of 7
    why can it be taken as pre increment of b followed by addition to the value of a?
    why is it taken as pre increment of a followed by addition to the value of b?
    how will the lexical analyser evaluate it?
    thanks for your reply in advance.bye take care.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    This is not to do with precedence but rather than the C++ (and C) compilers are greedy when parsing code. That is the compiler will grab as much of the file as possible when parsing it into tokens so b=+++a; is interpreted by the compiler as b=++ +a; and b=---a; as b=-- -a;.

    This shows a difference between the + and - operators. It appears that the compiler silently ignores + so +a is equivalent to a which is an lvalue (l for left*) and can be incremented. However -a performs an actual operation and the result is an rvalue (r for right*). You can not modify an rvalue so the compiler halts when it gets trys to interpret the -- operator since it modifies its operand.

    So in light of this your final expression c=a+++b; is interpreted by the greedy compiler as c=a++ +b;, a+b with a post increment of a.

    The real conclusion of all this is that you shouldn't concatenate you operators, use white space an parentheses to make sure the compiler is interpreting the operators as you intend them to interpreted.

    Comment

    Working...