Hi All,
I have one question regarding the code mentioned bellow.
#include<stdio.h>
int main(void)
{
unsigned int i = 5;
printf("\n i = %d i<<2 = %d i>>2 =%d\n",i,i<<=2,i>>=2);
return 0;
}
The output of the following code is as mentioned bellow.
i = 4 i<<2 = 4 i>>2 =1
I know the behavior of the code is undefined because
1) Order of evaluation of function arguments are not defined by C
standard.
Actually, that is both not true and does not make the behavior
undefined. The order of evaluation of function arguments is
"unspecified" by the C standard, which is a distinct type of behavior
completely different than "undefined".
Unspecified behavior means that the compiler (or more specifically,
the programmers who wrote the compiler) must pick some order, but they
do not have to document what it is, nor does it have to be consistent.
Consider:
#include <stdio.h>
int val(void)
{
static int x = 3;
return x++;
}
int main(void)
{
printf("%d %d\n", val(), val());
return 0;
}
This code has "unspecified behavior", but not "undefined behavior".
The compiler must generate code to call val() twice. The result of
one of these calls is passed as the second argument to printf(), the
result of the other call is passed as the third argument to printf().
The output can be either:
3 4
....or
4 3
....and the compiler documentation does not have to specify which. In
fact it may change from one to the other when the compiler is invoked
with different options.
There is no undefined behavior here, because each time the value of
'x' is modified, it is inside its own function, which introduces a
sequence point.
And since there is no undefined behavior involved, the program must
output one of these two sequences here, there are no other
possibilities allowed.
My question is
Does the following code not trying to modify the value of "i " with
in one sequence point ?
In fact, the one and only reason your code example has undefined
behavior is because it violates two rules relating to sequence points,
not just one.
First, the value of 'i' is indeed modified twice without an
intervening sequence point.
Second, the value of 'i' is accessed other than in to determine its
new value.
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://c-faq.com/
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html