if (_1_HOUR < count_value < _2_HOUR) {...}
This code snippet generates a warning in MPLAB X (It apparently compiles with the XC16 compiler). But I feel it should be an Error. The correct code (IMHO) is:
if ((count_value >_1_HOUR) && (count_value < _2_HOUR)) {...}
I looking for the C programming rule that covers this - does anyone know what that is? Thanks.
CodePudding user response:
looking for the C programming rule that covers this - does anyone know what that is?
Since you asked, the C 2018 rules that cover this grammatically are:
- 6.5.8 says a
relational-expression
may berelational-expression < shift-expression
. - Substituting this into its first operand,
relational-expression
may be arelational-expression < relational-expession < shift-expression
. - 6.5.8 also says a
relational-expression
may beshift-expression
. So we can substitute this into the above twice to haveshift-expression < shift-expession < shift-expression
. - 6.5.7 says a
shift-expression
may beadditive-expression
. - 6.5.6 says an
additive-expression
may bemultiplicative-expression
. - 6.5.5 says a
multiplicative-expression
may becast-expression
. - 6.5.4 says a
cast-expression
may beunary-expression
. - 6.5.3 says a
unary-expression
may bepostfix-expression
. - 6.5.2 says a
postfix-expression
may beprimary-expression
. - 6.5.1 says a
primary-expression
may beidentifier
orconstant
. - Therefore, a
relational-expression
may beidentifier < identifier < identifier
, which can be_1_HOUR < count_value < _2_HOUR
(or, if any of those are macros that expand to constants or other expressions, similar rules apply).
The rules that cover this semantically are:
- 6.5.8 3 says both operands to
<
shall have real type (integers or floating-point numbers) or both shall be pointers (with certain restrictions). Presumably both_1_HOUR
andcountvalue
have integer or floating-point type, satisfying the former. - 6.5.8 6 says “… The result has type
int
.” Thus, when the operands of the second<
are_1_HOUR < countvalue
and_2_HOUR
(also presumably integer or floating-point), they also satisfy 6.5.8 3.
CodePudding user response:
I feel it should be an Error
Well, it's not. The code is perfectly valid and has defined behavior.
if (_1_HOUR < count_value < _2_HOUR) {...}
If the result of 1_HOUR < count_value
(which is 0
or 1
in arithmetic context) is less than _2_HOUR
then {...}
Your X16 compiler probably supports these options that could help you though:
-Wall -Wextra -Werror -pedantic
I'm unsure if it also supports -pedantic-errors
. The doc was a bit fuzzy.
`