#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    1
    Rep Power
    0

    Question Usage of increment operator in output


    #include<stdio.h>
    void main()
    {
    int i;
    i=3;
    printf("%d%d",i,i++);
    }
    output of this is displayed as 43 y??? :confused:
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Posts
    156
    Rep Power
    34
    Originally Posted by varshc1
    Code:
    #include<stdio.h>
    void main()
    {
    	int i;
    	i=3;
    	printf("%d%d",i,i++);
    }
    output of this is displayed as 43 y??? :confused:
    Because using and updating an object without an intervening sequence point is undefined behaviour.

    Basically an object is a variable.
    Very basically a sequence point is the semicolon at the end of a statement.

    In your printf("%d%d", i, i++) statement, you use the value of i and update it in the same expression originating UB.

    You never ever want to write programs that contain UB!

    So ... don't do that. Write your program as one of the following alternate options:

    Code:
    #include<stdio.h>
    int main(void)
    {
    	int i, j;
    	i = 3;
            j = i++;
    	printf("%d%d\n", i, j);
    }
    Code:
    #include<stdio.h>
    int main(void)
    {
    	int i;
    	i = 3;
    	printf("%d%d\n", i, i);
            i++;
    }

IMN logo majestic logo threadwatch logo seochat tools logo