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
310 views
in Technique[技术] by (71.8m points)

c - Yoda Conditions and integer promotion

When comparing a type larger than int, with an integer constant, should I place the constant on the left or the right to ensure the correct comparison is performed?

int64_t i = some_val;
if (i == -1)

or should it be:

if (-1 == i)

Are there any circumstances in which either case is not identical to comparison with -1LL (where int64_t is long long)?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

It doesn't matter whether you put it on the right hand side or the left hand side; the == operator is completely symmetrical.

If both operands to the == operator have arithmetic type, as in this case, then the "usual arithmetic conversions" are applied (C99 §6.5.9). In this case, the rule that applies is:

If both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank. (C99 §6.3.1.8)

So the -1 is converted to int64_t. -1LL makes no difference.


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

...