0

This code triggers a warning with -Werror=conversion (GCC 10.1), and I don't understand why:

std::uint16_t i = 24, j = 12, k = 13;
std::uint16_t x = (i >> j) & k;

error: conversion from ‘int’ to ‘uint16_t’ {aka ‘short unsigned int’} may change value [-Werror=conversion]

According to cppreference, the return type of the right shift operator is simply the type of its LHS, which should be std::uint16_t. Adding two std::uint16_t should produce another std::uint16_t, so why am I getting a warning?

Note that everything works just fine if I do this:

std::uint16_t i = 24, j = 12, k = 13;
std::uint16_t x = (i >> j);
std::uint16_t y = x & k;
Touloudou
  • 2,079
  • 1
  • 17
  • 28
  • Arithmetic on integers smaller than `int` causes them to be promoted to `int` before the arithmetic. It's called integral promotion. – Aykhan Hagverdili Oct 09 '21 at 09:01
  • you are looking at the wrong table. The table on the page you link is "prototye examples for class T", it is signatures of typical custom implementations. `uint16_t` is not a class type. Read on: "Conversions If the operand passed to an arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-rvalue conversion, if applicable), the operand undergoes integral promotion" – 463035818_is_not_an_ai Oct 09 '21 at 09:01
  • Oh right I had forgotten about that. But then, why doesn't the second code sample give me any warning? x and y are narrowing conversions. – Touloudou Oct 09 '21 at 09:09

0 Answers0