Search code examples
cundefined-behaviorassignment-operatorpost-increment

b=b++ assignment unexpected result


I wrote this text code

int b=5;
int main()
{
    b=b++;
    printf("b = %d\n",b);
    return 0;
}

and I expected it to print "b = 6"; however, the result is "b = 5", i.e. b is not incremented. I know b=b++ is not a good practice but just to understand it, can anyone explain why it is not incrementing b please? What am I missing?


Solution

  • b++ means incrementing the value after it is used so for your case it should be ++b. When b is incrementing to 6 by b++ it is overwritten by assignment of b when it is 5.

    Just write it

    int b=5;
    int main()
    {
        // b=b++;
        b++;
        // or ++b;
        printf("b = %d\n",b);
        return 0;
    }