What's the output?

  • Thread starter Christopher Benson-Manica
  • Start date
C

Christopher Benson-Manica

Can you correctly identify the output of the following program,
without compiling it?

#include <stdio.h>

int main( void )
{
int a=1;
int b=0;
int foo=10+a?1:0+b?1:0;
printf( "%d\n", foo );
return 0;
}

Let's just say that I wish I had opened my desktop C references BEFORE
compiling and checking in certain changes I made. D'oh!
 
T

Tom St Denis

Christopher said:
Can you correctly identify the output of the following program,
without compiling it?

#include <stdio.h>

int main( void )
{
int a=1;
int b=0;
int foo=10+a?1:0+b?1:0;
printf( "%d\n", foo );
return 0;
}

Let's just say that I wish I had opened my desktop C references BEFORE
compiling and checking in certain changes I made. D'oh!

My initial guess was 1 [and I checked] and I questioned myself thinking 11.

This is why god invented () btw. Write it as

int foo = (10+a)?1:(0+b?1:0);

It becomes much clearer.

Tom
 
R

Rich Grise

Christopher said:
Can you correctly identify the output of the following program,
without compiling it?

Yes. :)
#include <stdio.h>

int main( void )
{
int a=1;
int b=0;
int foo=10+a?1:0+b?1:0;
printf( "%d\n", foo );
return 0;
}

Let's just say that I wish I had opened my desktop C references BEFORE
compiling and checking in certain changes I made. D'oh!

Wrong, huh? ;-)

Cheers!
Rich
 
J

Jack Klein

Can you correctly identify the output of the following program,
without compiling it?

#include <stdio.h>

int main( void )
{
int a=1;
int b=0;
int foo=10+a?1:0+b?1:0;
printf( "%d\n", foo );
return 0;
}

Let's just say that I wish I had opened my desktop C references BEFORE
compiling and checking in certain changes I made. D'oh!

Don't have to. The programmer who wrote that on my team would be
warned the first time. Transferred or fired if it happened a second
time.
 
A

Artie Gold

Jack said:
Don't have to. The programmer who wrote that on my team would be
warned the first time. Transferred or fired if it happened a second
time.
<facetious>
Wouldn't you expect your programmers to understand operator precedence?
</facetious>

<reality>
You are too kind.
</reality>

--ag
 
D

Dave Thompson

Can you correctly identify the [result of]
int foo=10+a?1:0+b?1:0;

Which is why to achieve what you wanted you should have done
int foo = 10+!!a+!!b;
which is read in "English"(?) as ten plus "absolutely the truth value
of a" plus similarly for b <G> <G> <G up SHRT_MAX>.

- David.Thompson1 at worldnet.att.net
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
anuragag27

Latest Threads

Top