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

    Join Date
    Jan 2013
    Posts
    74
    Rep Power
    2

    Explain please, increment


    Code:
    #include <stdio.h>
    
    main()
    {
    	int i=1;
    	int a=5+ i++;
    	int b=a*++i;
    	
    	printf("%d", b);
    	getch();
    }
    this is my simulation:

    int i=1; // i initialized to 1
    int a=5+ i++; // i++ is post-increment, therefore, 5+1=6
    int b=a*++i; // value of a which is 6 transferred to b, then ++i is pre increment, therefore the value is 2, 6*2=12

    when i run the program, the answer is: 18

    my question is how did ++i in int b became 3 when it was initialized to value 1, shouldn't that be 2 instead?
    Last edited by Kuiva; September 9th, 2013 at 12:24 AM. Reason: correction by SALEM, i interchanged post and pre increment
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,367
    Rep Power
    1870
    > int a=5+ i++; // i++ is pre-increment, therefore, 5+1=6
    > int b=a*++i; // value of a which is 6 transferred to b, then ++i is post increment, therefore the value is 2, 6*2=12
    Your explanations are wrong.
    i++ is post-increment (the ++ is AFTER the variable)
    ++i is pre-increment (the ++ is BEFORE the variable)
    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
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    8
    Rep Power
    0
    Hello,

    Here is the state of your data :

    int i=1;

    int a=5+ i++;
    a = 5 +1;
    a = 6 ; i = 2 (i++ increments i and returns the old value)

    int b=a*++i;
    b = 6*3; (++i increments i and returns the new value)
    b = 18; a = 6; i = 3.

    Do you understand now ?
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    74
    Rep Power
    2
    thank you Shadew :) i get it now

IMN logo majestic logo threadwatch logo seochat tools logo