amin__
amin__

Reputation: 1058

Why is this not working with printf() in c

I have the following code:

    int i=1;
    printf((i==1)?" ":"   " "hello");
    printf(" " "hello");

And I am astonished to see that the first printf only gives a space as output and the second printf outputs a space followed by the string hello. I was expecting output like second one in case of first one. But is there something here I am missing. Please help me with this ...

Upvotes: 3

Views: 215

Answers (5)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

The source of your confusion is the misunderstanding of when the concatenation is performed. Joining two consecutive string literals is done by the compiler at compile time, not by your program at run time. Therefore there is only one way to parse the first printf: both string literals belong to the "else" branch of the expression. You can test it by setting i to zero and observing the output.

Upvotes: 1

abelenky
abelenky

Reputation: 64730

C automatically combines two adjacent string literals together.

So your parameter to the second printf: " " "hello" gets joined together to become " hello", which is then printed out normally.

Other answers have explained why your first printf works the way it does, which should be pretty obvious.

Upvotes: 2

Cat Plus Plus
Cat Plus Plus

Reputation: 129954

String literal joining is a lexical feature, which means this:

(i==1) ? " " : "   " "hello"

is the same as this:

(i==1) ? " " : "   hello"

It should now be pretty obvious why you get the result you get.

Upvotes: 8

Levon
Levon

Reputation: 143122

Since the condition tested in the ternary operator (i==1) evaluates to true, it returns the expression right after the ?.

The semantics of the ternary operator are something like this:

test_something?if_true:not_true

Your printf statement works as it should.

Upvotes: 1

Ry-
Ry-

Reputation: 225164

i == 1 is true, so the ternary operator evaluates to the first of the two options, " ". Not at all surprising.

Upvotes: 2

Related Questions