Thread: help with post and pre increment operators

  1. #1
    Registered User
    Join Date
    Sep 2012
    Posts
    1

    help with post and pre increment operators

    Hello,
    I am new to this forum.

    I have a doubt in the post and pre increment operators.

    Code:
    #include<stdio.h>
    int main()
    { 
           int d=1,c;
           c= d++ + ++d + ++d;
           printf("%d    %d",c,d);
           return 0;
    }
    I get c as 7 and d as 4 .. Please explain me how..

  2. #2
    Registered User
    Join Date
    Jul 2012
    Posts
    8
    I am getting c equal to 9 and d equal to 4 help with post and pre increment operators-verde-gif.



    That is because the values of variables are modified after their increments:


    Code:
    #include <stdio.h>
    
    
    int main(void)
    {
        int d = 1, c;
        c = d++ + ++d + ++d;
        //The line above would generate:  c = 2 + 3 + 4;
        //Now "c" is equal to 9 (2 + 3 + 4) and "d" is equal to 4.
        printf("%d    %d", c, d);
        getchar();
        return 0;
    }


    I hope that I have helped help with post and pre increment operators-smiled-gif.

  3. #3
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    948
    Quote Originally Posted by electroboy View Post
    Code:
           c= d++ + ++d + ++d;
    This code exhibits undefined behavior. The expression itself is ambiguous because each term can be evaluated in any order, and the compiler is free to do so. Different compilers (or different compiler versions or even different optimization settings in the same compiler) can give you different results, and they would still be correct.

    See Expressions for more information about expressions.

  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
    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. Post Increment an Pre Increment operators in c++
    By anil_ in forum C++ Programming
    Replies: 4
    Last Post: 11-12-2011, 08:27 PM
  2. How Does Increment Operators Work...??
    By ajayd in forum C Programming
    Replies: 37
    Last Post: 12-31-2008, 10:01 AM
  3. increment and decrement operators
    By ee0u22ba in forum C++ Programming
    Replies: 5
    Last Post: 10-18-2003, 04:57 AM
  4. Post increment and pre increment help
    By noob2c in forum C++ Programming
    Replies: 5
    Last Post: 08-05-2003, 03:03 AM
  5. Pre-incrementoperators and post-increment operators
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 12-26-2001, 06:25 PM