Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implicit conversion changes signedness 'int" to 'unsigned int"

I was using clang++ to compile the program and I need to compile it with no error in clang++. I got no error with other compilers.

The error line in the code is

memset(grid_, 0, sizeof(int) * x_quadrants * y_quadrants);

The whole function is like this:

Ocean::Ocean(int num_boats, int x_quadrants, int y_quadrants)
{
  grid_ = new int[x_quadrants * y_quadrants];
  memset(grid_, 0, sizeof(int) * x_quadrants * y_quadrants);
  x_quadrants_ = x_quadrants;
  y_quadrants_ = y_quadrants;
  boats_ = new Boat[num_boats];
  num_boats_ = num_boats;

  stats_.hits = 0;
  stats_.misses = 0;
  stats_.duplicates = 0;
  stats_.sunk = 0;
}

I am using memset so I won't get garbage value output when test with different driver. There's no need to provide command line for clang because I'm not allowed to change it.

like image 288
TommyLan Avatar asked Feb 11 '15 05:02

TommyLan


2 Answers

Replace

grid_ = new int[x_quadrants * y_quadrants];
memset(grid_, 0, sizeof(int) * x_quadrants * y_quadrants);

with just

grid_ = new int[x_quadrants * y_quadrants]();

Note the parenthesis, that tells the compiler you want this zero-initialized (or really value-initialization, which reduces to zero-initialization here).

Even better, use a std::vector instead of this dangerous DIY scheme.

like image 74
Cheers and hth. - Alf Avatar answered Nov 14 '22 21:11

Cheers and hth. - Alf


sizeof returns a std::size_t which is unsigned. You're multiplying with (signed) int variables, hence the warning if you enable -Wsign-conversion in clang.

You can static_cast the dimensions to unsigned to avoid the warning - add a guard against negative values (assert for instance) if needed.

(Your code might benefit from using a member initializer list.)

like image 2
Mat Avatar answered Nov 14 '22 21:11

Mat