Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

ternary operator without else in C

I want to use ternary operator without else in C. How do I do it.

(a)? b: nothing;

something like this. What do I use in nothing part?

question from:https://stackoverflow.com/questions/12260777/ternary-operator-without-else-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are using a ternary operator like that, presumably it could be replaced by:

if (a) { b; }

which is much, much better. (The intent is clearer, so the code is easier to read, and there will be no performance loss.)

However, if you are using the ternary operator as an expression, i.e.

printf("%d cat%s", number_of_cats, number_of_cats != 1 ? "s" : <nothing>);

a = b*c + (d == 0 ? 1 : <nothing>);

then the <nothing> value depends on the context it is being used in. In my first example, <nothing> should be "", and in the second it should be 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...