Thread: Strange result.Why?

  1. #1
    Registered User
    Join Date
    Jul 2017
    Posts
    4

    Strange result.Why?

    I happened to meet this code:
    Code:
    #include <stdio.h>
       
    int main(){
        int count = 0;;
        printf("%d%d%d%d",++count ,++count ,++count ,++count ) ;
    }
    
    I think the result is 1234.
    But the result is 
    Strange result.Why?-1-png
    emmmm....

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    It's undefined behaviour. You're not allowed to modify an object more than once between sequence points.
    Even if it was defined, the order in which the parameters are evaluated is not defined so it could just as well be 4321.
    4444 is an interesting result and shows that the implementation is definitely relying on you only modifying an object once within the parameters since it performs all the increments before pushing the values for the call.

    BTW, your compiler should give you a warning about that line. With gcc use the -Wall switch for more warnings.

  3. #3
    Registered User
    Join Date
    Jul 2017
    Posts
    4
    emmmm......That is to say if I use ++ operator,I cannot predict the value of the parameters?

  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
    > That is to say if I use ++ operator,I cannot predict the value of the parameters?
    No, if you use the ++ or -- on the same variable more than once (between sequence points), you're on your own.

    printf("%d %d\n", ++x, y++);
    is perfectly fine, because each variable has only one side effect between sequence points.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I test for a result, but any result over 1 fails
    By jeremy duncan in forum C++ Programming
    Replies: 10
    Last Post: 05-23-2012, 01:23 PM
  2. a strange result,could anyone help me?
    By wang8442 in forum C Programming
    Replies: 10
    Last Post: 12-05-2004, 09:42 AM
  3. strange strange functions
    By threahdead in forum C Programming
    Replies: 4
    Last Post: 10-13-2002, 05:31 PM
  4. Strange result when comparing two doubles
    By DarkDragon in forum C++ Programming
    Replies: 4
    Last Post: 05-04-2002, 08:59 PM
  5. strange result of after compiling a program
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 04-23-2002, 09:54 AM

Tags for this Thread