Mazen said:
I have learned the attempting to assign a value to a variable and
fetching the value of it in the same expression will produce an
undefined behaviour. What are some of the other cases that produce
undefined behaviour? This is interesting!
If that were true, C would not allow:
x = x + 1;
The wording is:
"Between the previous and next sequence point an object shall have its
stored value modified at most once by the evaluation of an
expression. Furthermore, the prior value shall be read only to
determine the value to be stored."
so you may read the value (x) to determine the value to be stored (x +
1). However, in your case, the problem was modifying the value twice.
To understand the rule, you have to know where the sequence points are in
a C program. The standard has a list (edited here for clarity):
1. The call to a function, after the arguments have been evaluated
2. The end of the first operand of the following operators: logical
AND &&; logical OR ||; conditional ?; comma , .
3. The end of a full declarator: declarators.
4. The end of a full expression: an initializer; the expression in an
expression statement; the controlling expression of a selection
statement (if or switch); the controlling expression of a while or
do statement; each of the expressions of a for statement; the
expression in a return statement.
5. Immediately before a library function returns.
6. After the actions associated with each formatted input/output
function conversion specifier.
7. Immediately before and immediately after each call to a comparison
function, and also between any call to a comparison function and
any movement of the objects passed as arguments to that call.
As has been pointed out, the comma in number 2 is the operator and does
not appear in a normal function call -- that comma is just syntax for
the call. Number 7 is about the internals of the qsort and bsearch
library functions.