Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a=(b++) have the same behavior as a=b++?

Tags:

c

gcc

I am writing a small test app in C with GCC 4.8.4 pre-installed on my Ubuntu 14.04. And I got confused for the fact that the expression a=(b++); behaves in the same way as a=b++; does. The following simple code is used:

#include <stdint.h>
#include <stdio.h>

int main(int argc, char* argv[]){
    uint8_t a1, a2, b1=10, b2=10;
    a1=(b1++);
    a2=b2++;

    printf("a1=%u, a2=%u, b1=%u, b2=%u.\n", a1, a2, b1, b2);

}

The result after gcc compilation is a1=a2=10, while b1=b2=11. However, I expected the parentheses to have b1 incremented before its value is assigned to a1.

Namely, a1 should be 11 while a2 equals 10.

Does anyone get an idea about this issue?

like image 374
user5055706 Avatar asked Jun 27 '15 10:06

user5055706


1 Answers

However, I expected the parentheses to have b1 incremented before its value is assigned to a1

You should not have expected that: placing parentheses around an increment expression does not alter the application of its side effects.

Side effects (in this case, it means writing 11 into b1) get applied some time after retrieving the current value of b1. This could happen before or after the full assignment expression is evaluated completely. That is why a post-increment will remain a post-increment, with or without parentheses around it. If you wanted a pre-increment, place ++ before the variable:

a1 = ++b1;
like image 173
Sergey Kalinichenko Avatar answered Oct 09 '22 01:10

Sergey Kalinichenko