Home > Software design >  C compiler (X16) warning, but should be an error
C compiler (X16) warning, but should be an error

Time:09-24

 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 be relational-expression < shift-expression.
  • Substituting this into its first operand, relational-expression may be a relational-expression < relational-expession < shift-expression.
  • 6.5.8 also says a relational-expression may be shift-expression. So we can substitute this into the above twice to have shift-expression < shift-expession < shift-expression.
  • 6.5.7 says a shift-expression may be additive-expression.
  • 6.5.6 says an additive-expression may be multiplicative-expression.
  • 6.5.5 says a multiplicative-expression may be cast-expression.
  • 6.5.4 says a cast-expression may be unary-expression.
  • 6.5.3 says a unary-expression may be postfix-expression.
  • 6.5.2 says a postfix-expression may be primary-expression.
  • 6.5.1 says a primary-expression may be identifier or constant.
  • Therefore, a relational-expression may be identifier < 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 and countvalue 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.

`

  • Related