Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does g++ 4.8.1 issue a conversion warning

Tags:

c++

gcc

When I compile the code below with g++ 4.8.1 (64bit) in this way:

$ g++ -Wconversion -o main main.cpp

I get this result:

main.cpp: In function ‘int main()’:
main.cpp:12:20: warning: conversion to ‘int’ from ‘long unsigned int’ may alter its value [-Wconversion]
   int i = sizeof(x)/sizeof(x[0]);
                    ^

My expectation would be that the compiler should be able to evaluate the expression at compile time. If you make a similar program in plain c, gcc works like a charm.

Should this be considered a bug in g++ (e.g. clang++ does not have this problem)?

if you change the problematic line to something like:

char c = 0x10000000/0x1000000;

then the compiler does not complain. This suggest that some constant evaluation is done before warning generation.

main.cpp:

#include <iostream>

struct foo {
  int a;
  int b;
};

foo x[50];

int main()
{
  int i = sizeof(x)/sizeof(x[0]);
  std::cout << i << std::endl;

  return 0;
}
like image 984
jedelbo Avatar asked Mar 21 '23 22:03

jedelbo


1 Answers

 int i = sizeof(x)/sizeof(x[0]);
 //int <-- std::size_t <-- std::size_t / std::size_t

The type of the expression sizeof(x)/sizeof(x[0]) is std::size_t which on your machine is unsigned long int. So conversion from this type to int is data-loss, if the source is bigger in size than the target.

Though, I agree that in your case, there would not be actual data-loss if the compiler actually computes the value, but I guess it applies -Wconversion before the actual computation.

like image 168
Nawaz Avatar answered Apr 01 '23 12:04

Nawaz