Skip to content

Add explicit casts at narrowing integer conversions - #127

Open
escherstair wants to merge 1 commit into
debevv:masterfrom
escherstair:fix/narrowing-conversion-warnings
Open

Add explicit casts at narrowing integer conversions#127
escherstair wants to merge 1 commit into
debevv:masterfrom
escherstair:fix/narrowing-conversion-warnings

Conversation

@escherstair

Copy link
Copy Markdown

In C, the operands of <<, |, *, + and / are promoted to int, so every one of these expressions has type int even when both operands are uint8_t/uint16_t. Assigning the result back to a narrow type is an implicit narrowing conversion, which compilers report under -Wconversion (GCC/Clang), /W4 (MSVC, C4244).

Every affected value is provably in range, so these casts document the intent rather than change behaviour:

  • get_2(), get_regs(), put_regs(), swap_regs() - byte swaps of a uint16_t; the result cannot exceed 0xFFFF.
  • nmbs_write_multiple_coils() - quantity <= 0x07B0, so (quantity + 7) / 8 <= 246.
  • nmbs_write_multiple_registers() - quantity <= 0x007B, so quantity * 2 <= 246.
  • nmbs_write_file_record() - count <= 122, so 7 + count * 2 <= 251.
  • nmbs_read_write_registers() - write_quantity <= 0x0079, so write_quantity * 2 <= 242.

Each bound is already enforced by the argument validation at the top of the corresponding function.

In C, the operands of `<<`, `|`, `*`, `+` and `/` are promoted to `int`,
so every one of these expressions has type `int` even when both operands
are `uint8_t`/`uint16_t`. Assigning the result back to a narrow type is an
implicit narrowing conversion, which compilers report under `-Wconversion`
(GCC/Clang), `/W4` (MSVC, C4244) and at the default warning level of the
NI LabWindows/CVI 2015 compiler.

Every affected value is provably in range, so these casts document the
intent rather than change behaviour:

* `get_2()`, `get_regs()`, `put_regs()`, `swap_regs()` - byte swaps of a
  `uint16_t`; the result cannot exceed `0xFFFF`.
* `nmbs_write_multiple_coils()` - `quantity <= 0x07B0`, so
  `(quantity + 7) / 8 <= 246`.
* `nmbs_write_multiple_registers()` - `quantity <= 0x007B`, so
  `quantity * 2 <= 246`.
* `nmbs_write_file_record()` - `count <= 122`, so `7 + count * 2 <= 251`.
* `nmbs_read_write_registers()` - `write_quantity <= 0x0079`, so
  `write_quantity * 2 <= 242`.

Each bound is already enforced by the argument validation at the top of
the corresponding function.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant