DEV Community

Discussion on: Type Safety in C++

Collapse
 
sandordargo profile image
Sandor Dargo

The compiler might or might not warn you if you demote or narrow variables.

Try this:

#include <iostream>

int main() {
  unsigned int i = -5;
  short x = (short)0x12345678L;
  std::cout << i << std::endl;
  std::cout << x << std::endl;
}
Enter fullscreen mode Exit fullscreen mode

There is no compiler warning at all.

On the other hand, if you use a {}-initialization, you'll receive a compiler warning about a narrowing conversion.

#include <iostream>

int main() {
  unsigned int i {-5};
  std::cout << i << std::endl;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
blender profile image
Saloni Goyal

Yes 🤩, the first method didn't give any warning. The second one gave a compiler error on Xcode.
error