Simple C program-please explain output.

[CODE]int main()
{
int a=7, t=0;
t=--a+--a+a+++a;
printf("%d",t);
}[/CODE]

output: 20

I could not understand why it prints '20' ? please explain it !

Comments

  • I'm a student of C myself. So please don't take my answer as an educated one.
    However, that program is very unclear (maybe even so for the compiler).
    Basically the expression goes:
    t=(--a)+(--a)... and this is where it gets unclear. Either the rest of the expression goes t=(--a)+(--a)+a+(++a) or t=(--a)+(--a)+(a++)+a. Both of which would have different answers technically. The compiler maybe has a default or prioritized way of reading that expression.


  • That expression is calculated as follows:

    [code]t=(--a)+(--a)+(a++)+a;[/code]

    First a gets decreased by 1 twice (--a) BEFORE they are added together

    (a++)+a means that a will be increased by 1 AFTER it has been added with a again. And since a is never used again after this it doesn't matter that a=6 now.

    Hence we get:
    5+5+5+5=20


Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories