C language - pre incrementation doubt

consider this program on C –

#include<stdio.h>
int main(int argc, char const *argv[])
{
    int a, c;
    a = 4;
    c = ++a + ++a;
    printf("%d", c);
}

OUTPUT → 12

Now consider this code –

#include<stdio.h>
int main(int argc, char const *argv[])
{
    int a, c;
    a = 4;
    c = ++a + ++a + ++a;
    printf("%d", c); 
}

OUTPUT → 19

In the first case both the ‘a’ got incremented to 6 and then added up but in the second case, the first two ‘a’ get incremented to 6 and only the last ‘a’ increments to 7 to give the final output of c as 19.

Can someone please explain why is it working this way??

a = 1
a = ++a+++a+++++++++a;

Find the spaces.

c = ++a+++a+++a;

c = (++a++)+(a++)+a ???
c = (++a)+(++(a++)+a ???
c = (++a)+(++a)+(++a) ???

I recommend never writing code that depends upon pre vs post increment differences. This sort of thing is best avoided.

1 Like

even if you apply brackets, all the outputs are the same as when you use space to separate them. So putting brackets in place of empty space doesn’t make any difference.

I agree but I am interested in knowing the working of this expression for better understanding :slight_smile:

Looks like it is compiler dependent.

#include <stdio.h>

int main()
{
    int a = 4;
    c = ++a+++a+++a;
    printf("%d", c);

    return 0;
}

error: lvalue required as increment operand

If you don’t know how your compiler works you can get creative and change some + to -, add more variables and debug and execute step-by step to reverse-engineer it.
You can also read compiler code, but you will probably discover that it is better to listen to JeremyLT’s advice.