Will a C conditional always return 1 or 0?

后端 未结 4 1356
不思量自难忘°
不思量自难忘° 2021-01-11 23:50

Do C conditional statements always return [1 or 0], or do they return [0 or \'something other than zero\']. I ask because:

pseudo code -

f

相关标签:
4条回答
  • 2021-01-12 00:20

    Rather than right shifting and left shifting back again to clear the LSB, I would bitwise-and it with 0xFE:

    register = register & 0xFE;
    

    [edit: assuming register is 8 bits. If not, adapt right hand operand as necessary]

    But yes, if shouldSend is a result of a conditional test then it is guaranteed by the standard to be either 0 or 1. If there's any doubt about whether shouldSend could be generated from anywhere else it would be wise to put in the sort of precaution you have, or something like

    register = register | (shouldSend ? 1 : 0);
    
    0 讨论(0)
  • 2021-01-12 00:22

    Doesn't matter if it is specified or not. It is best to always test against false and be explicit about your or-equals values. This removes any worry about compiler implementations and is clearer and more maintainable.

    0 讨论(0)
  • 2021-01-12 00:23

    Yes. This is guaranteed in C99. I don't have the C89 spec handy. Of course, compiler implementers have been known to make mistakes on occasion so YMMV.

    C99 specifies the following in paragraph 6 of 6.5.8 Relational operators:

    Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.

    The same or similar clauses appear in paragraph 3 of 6.5.9 Equality operators, paragraph 3 of 6.5.13 Logical AND operator, and paragraph 3 of 6.5.14 Logical OR operator.

    0 讨论(0)
  • 2021-01-12 00:37

    Standard specifies that the result is always integer value equals to 0 or 1

    6.5.8 Relational operators

    Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.92) The result has type int.

    0 讨论(0)
提交回复
热议问题