Hi Guys ,
As per the operator precedence table, unary operators have a higher precedence over ternary operator,then in the below given example ,why this rule is not followed ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{
int a = 1;
int b = 0;
int c = 9;
int x = (a>1)? ++b :++c ;
cout<<"\n Val of X = \t"<< x ;
cout<<"\n Val of B = \t"<< b ;
cout<<"\n Val of C = \t"<< c ;
return 0;
}
The output being :
Val of X = 10
Val of B = 0
Val of C = 10.
what I infer from the output is first the condition is matched and based upon that pre-increment is done .
However ,pre -increment has a higher precedence over ternary operator ,so how does this thing is performed by the compiler ?
One thing I must agree that , unary operation is a part of the ternary operation ,does that means in such scenarios ,i.e where a higher precedence operator is a sub part of lower precedence, the compiler executes the lower precedence operation first .
> for any operator there is "associativity " and order of preference ,they why ternary first and then unary ?
The C++ standard does not directly specify the precedence of operators; they are inferred from the specification of the grammar.
Re. the conditional operator: first ? second : third
Every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second or third expression. http://eel.is/c++draft/expr.cond#1
Note that this is the C++ rule; the C rules are somewhat different.
For example, this is valid C++ , but invalid in C
1 2 3 4 5
int main()
{
int a = 5, b = 0 , c = 0 ;
a < 10 ? b = 2 : c = 8 ;
}