-4

I'm reading a C bug material and it said that:

In a single expression itself, we may not surely guess the order of the side effects. As in the following part of code, depending on the compiler used, i/++ might be either 0 or 1

...
int i = 1;
int ii = i /++ i ;
...

Could you tell me the reason ?

This post has close problem Why does the expression a = a + b - ( b = a ) give a sequence point warning in c++?

Community
  • 1
  • 1
Van Tr
  • 5,889
  • 2
  • 20
  • 44
  • It has nothing to do with operator precedence. In your example, you only have one operator on the right hand side of the assignment, so operator precedence is clearly irrelevant. – Crowman Feb 21 '16 at 02:50
  • no, there are 3 operator totally, `=` and `/` and `++` – Van Tr Feb 21 '16 at 02:53
  • Is space between ++ and i a typo? or that was intentionally added? – Umamahesh P Feb 21 '16 at 02:55
  • I said "on the right hand side of the assignment", but fair point, `++` is an operator too. It still has nothing to do with operator precedence, since the `++` operator is not competing with any other (it can't bind to the `/` operator, naturally), so there are no precedence questions to resolve. – Crowman Feb 21 '16 at 02:55
  • I said 3 for totally, if on the right hand side there are 2 not 1 – Van Tr Feb 21 '16 at 02:56
  • 1
    I don't think this question is duplicate with the marked question, they are different in tag and the problem is quite far different. – Van Tr Feb 21 '16 at 03:04
  • 2
    The dup in the colse-reason is wrong. Because that is a C++ question. But there is another dup in the info page for C whihc should have been used as close-reason.. – too honest for this site Feb 21 '16 at 03:07

1 Answers1

1

Operator precedence is about making tree, and it won't affect the order of evaluation.

The tree should look like ((ii) = ((i) / (++(i)))) in every compiler.

On the other hand, the evaluation order is unspedified, so we cannot tell which of left hand i and right hand ++i is evaluated earlier. If former is evaluated first, the expression will be 1 / 2, but if the latter is evaluated first, the expression will be 2 / 2.

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 v alue shall be read only to determine the value to be stored. 73)
3 The grouping of operators and operands is indicated by the syntax. 74) Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • 2
    This is *undefined behaviour* - the possible results are not limited to the two cases you listed – M.M Feb 21 '16 at 02:58