Jump to content

effect of b = a++ + a++

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
qwertyuiop

qwertyuiop

    Newbie

  • Members
  • Pip
  • 2 posts
what is the effect of fllowing code n values of a and b
b = 0;
a = 1;
b = a++ + a++;

#2
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
The result will be:

a = 3
b = 2

When you're using the post-increment-operator, the value of the variable will be incremented, but it will return the old value. In the following code, the variable will have the incremented value.

c = 10
d = c++
// c = 11
// d = 10

#3
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Void, have you tested that? (I haven't) My logic was the following:

Expanding on that:
b = a++ + a++
the first a++ increments a to 2, returns 1, leaving an intermediate calculation of:
b = 1 + a++
the remaining a++ increments a to 3, returns 2, leaving an intermediate calculation of:
b = 1 + 2

Result: a = 3, b=3.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#4
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
Actually, I made something like you did, but before I posted it, I tested it using GCC, and I got kinda surprised. The result was as I wrote in my post. For some reason does neither of the a's increment more than one, before the statement has ended. It could be bug - I don't know.

This is the little C-program I used for testing.
#include <stdio.h>

int main()
{
        int a = 1;
        int b = 0;

        b = a++ + a++;
        printf("a: %d\nb: %d\n", a, b);

        return 0;
}
gcc test.c -o test
$ ./test
a: 3
b: 2


#5
G_Morgan

G_Morgan

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 537 posts
i++ is post increment so should increment the value after the statement has been executed.

Try ++a and it should then give a = 3, b = 6;

I wouldn't actually write any code like that. It's the reason a lot of people dislike C.

//edit - just thought I'd add what the compiler will convert these things to

[HIGHLIGHT="C"]
b = a++ + a++;
/*converts to */
b = a + a;
a += 1;
a += 1;

-------------
b = ++a + ++a;
/*converts to*/
a += 1;
a += 1;
b = a + a;
[/HIGHLIGHT]

#6
Guest_Jordan_*

Guest_Jordan_*
  • Guests
Nice work Winged/v0id/G_Morgan. +Rep given to all three of you.