Shortcut to remember the Order of Evaluation and Precedence of Operators in C [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:47:02

问题:

This question already has an answer here:

is there any shortcut or bestway to remember the precedence and order of evaluation in C beacause it plays the main role and i or (most of us) usually forgets and end up with the mess. Please Help me....

i want to give an example for this... say..

void main()   {       int a=1;       a = a++ + ++a;       printf("%d",a);   }//prints 5;   void main()   {       int a=1;       int x;       x = a++ + ++a;       printf("%d",x);   }//prints 4;   

also the expression
x = ++a + a++;
gives a different result

i hope that if post increment have high priority then a++ should be evaluated first please clear me if iam wrong and please explain me how it works..

回答1:

First of all, expressions of the form a++ + ++a, ++a + a++, etc., result in undefined behavior; any result is possible. From the language standard (n1256):

6.5 Expressions
...
2 Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.72) Furthermore, the prior value shall be read only to determine the value to be stored.73)
...
72) A floating-point status flag is not an object and can be set more than once within an expression.

73) This paragraph renders undefined statement expressions such as
         i = ++i + 1;         a[i++] = i; 
while allowing
         i = i + 1;         a[i] = i; 

So, don't do that.

A well-defined expression like x = a++ + ++b will be parsed as x = ((a++) + (++b)); both forms of the ++ operator have higher precedence than addition, and addition has higher precedence than assignment. The result of the expression will be the same as x = a + (b + 1).

Secondly, remember that the ++ and -- operators have a result and a side effect, as shown below:

 Expression          Result         Side effect ----------          ------         -----------        i++               i            i = i + 1        ++i           i + 1            i = i + 1        i--               i            i = i - 1        --i           i - 1            i = i - 1 

Important note to remember: the side effect doesn't have to be applied immediately after the expression is evaluated; it only has to be applied before the next sequence point. It's possible for x = a++ + ++b to be evaluated as follows:

t1 = a; t2 = b + 1; x = t1 + t2; b = b + 1; a = a + 1;   

In this case, the updates to a and b are deferred until after the addition and assignment to x.

As far as precedence is concerned, here is the general order from high to low:

  1. Postfix operators (all have the same precedence, so sequences of operators will be evaluated left-to-right)
    • array subscript operator []
    • function call operator ()
    • component selection operators . and ->
    • postfix ++ and --
  2. Unary operators (all have the same precedence, so sequences of operators will be evaluated left-to-right)
    • prefix ++ and --
    • sizeof
    • bitwise negation operator ~
    • logical negation operator !
    • unary sign operators - and +
    • address-of operator &
    • dereference operator *
  3. Cast expressions ( type name )
  4. Multiplicative operators *, /, %
  5. Additive operators + and -
  6. Shift operators << and >>
  7. Relational operators <, >, <=, >=
  8. Equality operators == and !=
  9. Bitwise AND &
  10. Bitwise XOR ^
  11. Bitwise OR |
  12. Logical AND &&
  13. Logical OR ||
  14. Conditional operator ?:
  15. Assignment operators =, +=. -=, *=, /=, %=, <<=, >>=, &=, ^=, |=
  16. Sequential (comma) operator ,

So, expressions like *x++ are parsed as *(x++), since the postfix ++ has higher precedence than the unary *. Similarly, sizeof x + 1 is parsed as (sizeof x) + 1, since sizeof has higher precedence than addition. An expression like p++->x is parsed as (p++)->x; both postfix ++ and -> operators have the same precedence, so they're parsed from left to right.

This is about as short as shortcuts get; when in doubt, use parentheses.



回答2:

Do like the pros: add parentheses when you are unsure. Then you don't have to remember, plus the code will be easier to read.



回答3:

There is a shortcut to remember C operator Precedence.

PUMA IS REBL ( spell "REBL" as if "REBEL").

"I" in IS does not represent any operator and used for completion of the sentense.

P - Primary

U - Unary

M - Multiplicative

A - Additive

S- Shift

R- Relational

E- Equality

B- BitWise ( & > ^ > |)

L- Logical ( logical && > logical ||)

and the last three operators are

Ternary(conditional),

Assignment and

Comma.

for Assosiativity All except Unary,Assignment and Ternary are Left to Right.

For PUMA's full story please see the comments.



回答4:

If you find it confusing then so will anyone reading your code. If in doubt, use brackets to emphasize.



回答5:

I agree with the other post, always try to use parenthesis. But, if you don't want to, here you go, print this out and stick it next to your computer or something.



回答6:

Thou shalt not rely on your memory when operator precedence is concerned. Only in obvious cases. Which are - presedence of arithmetic operators, + - * / %. It is also with knowing that ++ and -- have higher precedence than * to be able to read correctly expressions like *p++ = *q++; Bitwise operations have crazy precedence rules. ALWAYS use parentheses for those.



回答7:

To learn operator precedence try this: 1:ARLA means: A-> Arithmetic operator R->Relational operator L->Logical operator A-> Assignment operator 2: BODMAS B=brackets first( (,) ) O=orders(like power and square etc.,) D=division(/) M=multiplication(*) A=addition(+) S=substraction(-)



回答8:

it is simple calculation When you write int a=1; x= a++ + ++a; Due to prefix increment operator (in ++a) the value of 'a' will become equal to 2 Therefore the current expression is equivalent to x= 2+2; // x=4 As soon as control goes to next line value of a increases by 1 due to postfix operator, now a =3

Now examine this statement int a=1; a= a++ + ++a; In this statement as explained above value of 'a' will be equal to the expression a= 2+2;. // means a=4 But due to postfix increment operator (a++) the value of a increases by 1 as soon as control shift to next line in the program. Therefore printf (%d,a); prints 5 I hope this will clear your doubt



回答9:

In C, the precedence table specify the order of evaluation of expression and also specify the association rules. Using that rule we can evaluate the equal priority operator(R->L OR L->R) in a expression.
You specify,
a = 1;
x = a++ + ++a;
1: ++a then exp: a(2)++ + 2 = 4 assign to x
2: and then increment a , becomes a = 3

suppose, a = a++ + ++a; then
increment a
2 + 2 assign to a(4). increment a(5).



回答10:

Promod answer or his explanations is not correct

The correct method to remember is

Of all the pre operators -pre increment has highest priority

And of all the post increment operations -post increment has least priority

Addition has lower priority than both pre and post increment operators

Now consider the fact that Pre increment falls in the category of Right to left

And Post increment falls in the class of Left to right

Taking the two cases into consideration one can work out the code

i = 1; i=i++ + ++i + ++i + i++; 

To be not 14 but 12

Middle two expressions are evaluated to 4 then 4+4+4

"Postfix increment/decrement have high precedence, but the actual increment or decrement of the operand is delayed (to be accomplished sometime before the statement completes execution). "

This is the proof link enter link description here



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!