LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C programming increment and decrement doubt (https://www.linuxquestions.org/questions/programming-9/c-programming-increment-and-decrement-doubt-810226/)

shariefbe 05-26-2010 09:55 AM

C programming increment and decrement doubt
 
Hello friends,
I have an big doubt in increment and decrement in c programming
i am trying to compile the below code in gcc
Code:

#include<stdio.h>
main()
{
int a=10,b=12;

printf("\n%d\n%d\n%d\n%d\n%d\n",a++,++a,a--,--a,a);
}

and i am getting the below output
Code:

9
10
9
10
10

i am very much confused. how it is parsing and how i will get this output?please explain me

johnsfine 05-26-2010 09:59 AM

It is not correct to change the same variable more than once without a "sequence point".

Nothing in the C standard tells the compiler the sequence in which your a++ and ++a are executed. So the results are undefined.

brazilnut 05-26-2010 10:38 AM

oh what fun, do before, do after...

Code:

#include<stdio.h>
main()
{
        int a=10;
        printf("%d\n",a++);
        printf("%d\n",++a);
        printf("%d\n",a--);
        printf("%d\n",--a);
        printf("%d\n",a);
       
        printf("\n");
       
        a = 10;
        printf("%d\n",++a);
        printf("%d\n",a++);
        printf("%d\n",--a);
        printf("%d\n",a--);
        printf("%d\n",a);
}

resulting in...

Code:

10
12
12
10
10

11
11
11
11
10

I love this second part of the example...

paulsm4 05-26-2010 10:52 AM

Hi -

Code:

#include<stdio.h>

int
main(int argc, char *argv[])
{
  int a=10,b=12;
  /* WRONG: the evaluation order for this expression is UNDEFINED! */
  printf("\n%d\n%d\n%d\n%d\n%d\n",a++,++a,a--,--a,a);
  return 0;
}

Johnsfine is absolutely correct. Different compilers (or even different versions of the SAME compiler) might give you different results; any of which might be different from what you expect.

Here are two more links that might help:

http://www.daniweb.com/forums/thread100183.html
http://c-faq.com/expr/index.html

'Hope that helps .. PSM


All times are GMT -5. The time now is 06:31 AM.