Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is compiler keep warning me that narrowed from `int` to `uint8`?

Tags:

c++

I checked again and aigain, I'm sure that I did not cast uint8 to int implicitly in my code, nither forwardly nor backwardly.

// main.cpp
#include <iostream>
using std::cout, std::endl;

using uint8 = unsigned char;

struct Vector {
  uint8 x, y, z;

  Vector operator+(const Vector& v) const {
    return Vector{this->x + v.x, this->y + v.y, this->z + v.z};
  };
  void operator+=(const Vector&);
  void operator-(const Vector&) const;
  Vector operator-=(const Vector&);
  Vector operator*(const uint8 scaler) const;
  Vector Corss(const Vector&, const Vector&) const;
  void Corss(const Vector&);
  Vector Dot(const Vector&, const Vector&) const;
  void Dot(const Vector&);
};

std::ostream& operator<<(std::ostream& os, Vector& vec) {
  return os << "(" << (unsigned)vec.x << "," << (unsigned)vec.y << ","
            << (unsigned)vec.z << ")";
}
int main() {
  Vector v1{1, 2, 3};
  Vector v2{1, 1, 1};
  Vector v3 = v1 + v2;
  cout << v1 << endl;
  cout << v2 << endl;
  cout << v3 << endl;
}

prompt:

$g++ main.cpp -std=c++17 -O0 -g -Wall -Wextra
main.cpp: In member function 'Vector Vector::operator+(const Vector&) const':
main.cpp:10:27: warning: narrowing conversion of '(((int)((const Vector*)this)->Vector::x) + ((int)v.Vector::x))' from 'int' to 'uint8 {aka unsigned char}' inside { } [-Wnarrowing]
     return Vector{this->x + v.x, this->y + v.y, this->z + v.z};
                   ~~~~~~~~^~~~~
main.cpp:10:42: warning: narrowing conversion of '(((int)((const Vector*)this)->Vector::y) + ((int)v.Vector::y))' from 'int' to 'uint8 {aka unsigned char}' inside { } [-Wnarrowing]
     return Vector{this->x + v.x, this->y + v.y, this->z + v.z};
                                  ~~~~~~~~^~~~~
main.cpp:10:57: warning: narrowing conversion of '(((int)((const Vector*)this)->Vector::z) + ((int)v.Vector::z))' from 'int' to 'uint8 {aka unsigned char}' inside { } [-Wnarrowing]
     return Vector{this->x + v.x, this->y + v.y, this->z + v.z};
                                                 ~~~~~~~~^~~~~
$./a.out
(1,2,3)
(1,1,1)
(2,3,4)
like image 717
kinyin Avatar asked Jan 02 '23 23:01

kinyin


1 Answers

Each term in the expression this->x + v.x &c. is widened automatically to an int, and the type of that expression is an int. This is because the arguments to + are narrower than an int. Your compiler then issues you a warning since you are initialising Vector elements which have a narrower type than int.

It's a fact of life in C++. You get the same effect with something like

auto a = 'a' + 'b';

a is an int type.

like image 63
Bathsheba Avatar answered Jan 05 '23 13:01

Bathsheba