0

I have a function which accepts a uint8_t variable. When I use the bitwise complement i.e. ~ operator on the parameter value, I get the following warning:

warning: conversion to 'uint8_t {aka unsigned char}' from 'int' may alter its value [-Wconversion]
   func(~ui); 

Here is a working example:

void func(uint8_t ui) {}

int main() {  

  uint8_t ui{0xF0};

  // Without compl operator it works
  func(ui);

  // Getting warning: conversion to 'uint8_t {aka unsigned char}' 
  // from 'int' may alter its value
  func(~ui); 

  // Here the ~ operator changes the 8-bit ui to 32-bit
  std::cout << "ui: " << std::bitset<sizeof(ui)*8>(ui) << std::endl;
  std::cout << "~ui: " << std::bitset<sizeof(~ui)*8>(~ui) << std::endl;

  return 0;
}

which generates the following output:

ui: 11110000
~ui: 11111111111111111111111100001111

I've read and tested the example at cppreference. They use a bitset which uses a byte storage per bit and does not elaborate on the case when using the operator only on a single byte. I also checked cplusplus which does not explain why either.

Thus, why can't you use the ~ operator (and I've checked the other bitwise operators as well) on a uint8_t without it changing the uint8_t to an int?

Jan Gabriel
  • 1,066
  • 6
  • 15

0 Answers0