Beginner C/C++

Moderators: None (Apply to moderate this forum)
Number of threads: 5430
Number of posts: 16951

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Simple C program-please explain output. Posted by hitesh_incept on 13 Sept 2012 at 3:17 AM
int main()
{
     int a=7, t=0;
     t=--a+--a+a+++a;
     printf("%d",t);
}


output: 20

I could not understand why it prints '20' ? please explain it !
Report
Re: Simple C program-please explain output. Posted by Kotik on 13 Sept 2012 at 6:01 PM
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.


Report
Re: Simple C program-please explain output. Posted by raxxa on 14 Sept 2012 at 8:57 AM
That expression is calculated as follows:

t=(--a)+(--a)+(a++)+a;


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





 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.