Thread: Odd printf behavior?

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    3

    Question Odd printf behavior?

    I just compiled the program below in Cygwin and on codepad

    int main()
    {
    int k=1;
    printf("%d, %d, %d\n", k, k++, k++);
    }

    In both cases the output was

    3, 2, 1

    Shouldn't it be the other way around?

    Any thoughts would be welcome.

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    You're engaging in undefined behavior due to sequence points. If you're being taught this, your instructor is an idiot.

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    90
    It is undefined what order the parameters of a function are evaluated in. In practice, many compilers will do them in the reverse order because that's how they get pushed on the stack, but don't depend on that.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Another dupe thread -> Odd printf behavior?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Apr 2011
    Posts
    3

    Cool Thanks!

    Quote Originally Posted by Clairvoyant1332 View Post
    It is undefined what order the parameters of a function are evaluated in. In practice, many compilers will do them in the reverse order because that's how they get pushed on the stack, but don't depend on that.
    Thanks, makes sense!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems reading entered race times C
    By loopymoo26 in forum C Programming
    Replies: 12
    Last Post: 05-23-2009, 07:38 AM
  2. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  3. making it portable.....?
    By ShadeS_07 in forum C Programming
    Replies: 11
    Last Post: 12-24-2008, 09:38 AM
  4. menu problem!!! need U R G E N T help!!!
    By catcat28 in forum C Programming
    Replies: 16
    Last Post: 11-19-2007, 01:32 PM
  5. Drawing tables in C
    By stanoman in forum C Programming
    Replies: 5
    Last Post: 10-09-2003, 10:14 AM

Tags for this Thread