Results 1 to 5 of 5

Thread: c output ...compiler dependent ?

  1. #1
    Join Date
    Sep 2008
    Beans
    116

    Thumbs down c output ...compiler dependent ?

    I understand that the output of the following code snippet is dependent upon the compilers.Can anybody explain the cases?

    Code:
    #include<stdio.h>
    main()
    {
    	int x=7;
            printf("%d %d %d\n",x++,++x,x++);
    	
    }
    OUTPUT in ubuntu 10.04 (gcc 4.4.3) : 9 10 7
    OUTPUT in dev c++ 4.9.9.2 ( gcc version 3.4.2): 9 9 7
    OUTPUT in vc++ 6.0: 8 8 7




    thanks in advance...

  2. #2
    Join Date
    Jul 2007
    Location
    Magic City of the Plains
    Beans
    Hidden!
    Distro
    Xubuntu 16.10 Yakkety Yak

    Re: c output ...compiler dependent ?

    Moved to Packaging and Compiling Programs.

  3. #3
    Join Date
    Sep 2009
    Beans
    1,293

    Re: c output ...compiler dependent ?

    Hazy in my mind, but I'll give it a go
    Code:
    printf("%d %d %d\n",x++,++x,x++);
    is an example of undefined behaviour, all that happens is that different compilers handle undefined behaviour in different ways. Technically the arguments that pre/post increment x are not guaranteed specifically to be carried out in any particular order so any compiler, or the same one with different flags, might choose to do any one of them first.

    As with most undefined behaviour its best understood by understanding the nature of sequence points, points throughout code that mean that all previous statements have been carried out and all side-effects to do with them are also finished.

    [EDIT]
    https://en.wikipedia.org/wiki/Sequence_point
    http://stackoverflow.com/questions/4...equence-points
    another one!
    http://stackoverflow.com/questions/3...-one-statement

  4. #4
    Join Date
    Jan 2010
    Location
    Kolkata India
    Beans
    Hidden!
    Distro
    Ubuntu

    Re: c output ...compiler dependent ?

    The C language clearly tells that certain things lead to undefined behavior .
    Please refer to wikipedia's page on [sequence point]http://en.wikipedia.org/wiki/Sequence_point[/URL] and [Undefined_behavior]http://en.wikipedia.org/wiki/Undefined_behavior[/URL]
    “Progress is made by lazy men looking for easier ways to do things”
    — Robert A. Heinlein

  5. #5
    Join Date
    Jan 2010
    Location
    Kolkata India
    Beans
    Hidden!
    Distro
    Ubuntu

    Re: c output ...compiler dependent ?

    try using the volatile type int .
    and observe the change in behavior .
    Code:
    volatile int x=7;
    “Progress is made by lazy men looking for easier ways to do things”
    — Robert A. Heinlein

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •