what is the effect of fllowing code n values of a and b
b = 0;
a = 1;
b = a++ + a++;
effect of b = a++ + a++
Started by qwertyuiop, Jan 20 2008 03:26 AM
5 replies to this topic
#1
Posted 20 January 2008 - 03:26 AM
|
|
|
#2
Posted 20 January 2008 - 04:06 AM
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
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
Posted 21 January 2008 - 10:26 AM
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.
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.
#4
Posted 21 January 2008 - 09:53 PM
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.
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
Posted 22 January 2008 - 02:49 AM
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]
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_*
Posted 22 January 2008 - 04:47 AM
Guest_Jordan_*
Nice work Winged/v0id/G_Morgan. +Rep given to all three of you.


Sign In
Create Account

Back to top









