This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

RE: Is this a gcc bug?


>From: Uros Bizjak [mailto:uros@kss-loka.si]
>Sent: 11 January 2001 10:11

>  This code produces a strange result on Solaris 2.5.1 with gcc 2.8.1:
>
>--cut here--
>
>#include <stdio.h>
>int main()
>{
>        int x = 0;
>        int y = 5;
>        int z = 15;
>
>        printf ("%i, %i, %i, %i\n", x,  x += y, x += 2, x += z); 
>        return 0;
>}
>
>--cut here--
>
>  It displays "22, 5, 7, 22".
>  I would expect the result to be "0, 5, 7, 22".

  The code isn't valid.  It is part of the language specification that you
cannot rely on the order of evaluation of arguments to a function call, nor
can you rely on when the side effects take place.  There's a technical
thing about these things called sequence points and how you're only allowed
to change the value of a variable once between them, but that's quite 
in-depth.  If you called 

   printf("%d %d %d\n", x++, x++, x++);

the compiler is free to pass the same value for all three occurrences of x
and add three to it after the function call, or to evaluate the arguments
from left to right and pass 0, 1, 2, or from right to left and pass 2, 1, 0,
or indeed (since the language spec says this is undefined behaviour) to 
output a program that plays space invaders when you run it.  Steer clear
of such ambiguous constructs and you'll be ok.

      DaveK
-- 
The Boulder Pledge: "Under no circumstances will I ever purchase anything 
offered to me as the result of an unsolicited email message. Nor will I 
forward chain letters, petitions, mass mailings, or virus warnings to large 
numbers of others. This is my contribution to the survival of the online
community." 


**********************************************************************
This email and any files transmitted with it are confidential and
intended solely for the use of the individual or entity to whom they
are addressed. If you have received this email in error please notify
the system manager.

This footnote also confirms that this email message has been swept by
MIMEsweeper for the presence of computer viruses.

www.mimesweeper.com
**********************************************************************

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]