Re: unexpected result



Jack Klein wrote:

On 8 Mar 2006 01:17:27 -0800, "Ankur" <ankur.mcp@xxxxxxxxx> wrote in
comp.lang.c:

#1, DON'T TOP POST IN THIS GROUP. I have put your reply where it
belongs, after the original post.


ashu wrote:

hi
look at this code

include <stdio.h>
int main(void)
{
int i,j=2;
i=j++ * ++j * j++;
printf("%d %d",i,j);
return 0;
}

acc. to me the values of i & j are 27,5 respectively & rightly so as i


ran this on turbo c++ compiler but if i ran this on lcc-win32 compiler


i got 32 & 5 for i & j respectively.
why this is so

hi anshu
it all compiler depenedent
in lcc-win32 compiler
first the code run on right to left
means i=4*4*2
it give 32 for i
but in turboc compiler it execute code left to right and take big value
among it i.e. 3
so thats y its give 27.


No, it is not "all compiler dependent", it is undefined behavior.
There is no right result, there is no wrong result, as far as the C
language is concerned there is no need for a result at all.

There's always a result. But the result may not be as expected. Hence unexpected behavior.

--
jay
.



Relevant Pages

  • Re: whats wrong with atof() and casting?
    ... The return type of the function was int, ... Since atofDOES NOT return an int, this is wrong and undefined behavior. ... Note that a compiler is not required to do anything at all when you ... There is no requirement in the C standard that they do. ...
    (comp.lang.c)
  • Re: whats wrong with atof() and casting?
    ... The return type of the function was int, ... the compiler generates a call to a ... atofDOES NOT return an int, this is wrong and undefined behavior. ... There is no requirement in the C standard that they do. ...
    (comp.lang.c)
  • Re: Colon (:) syntax in defining fields in a struct
    ... you're missing the fact that printf() has no way of knowing the ... corresponding argument is going to be of type int. ... so the compiler has no way of knowing what's in it. ... is that it's undefined behavior, meaning that the standard places no ...
    (comp.lang.c)
  • Re: structure and union queries
    ... off and you still get undefined behavior. ... Assuming float and int are ... // Compiler leaves a copy of 66.0 in a floating point register. ... where such an "optimization" might seem ...
    (comp.lang.c)
  • Re: Why this works???
    ... OK, What am I missing? ... int, a return from the initial call to the main function is equivalent ... If we assume that the compiler chosen is a C89 compiler and not a C99 ... then we can have undefined behavior. ...
    (comp.lang.c)