1

Seeing as how it's often times a bad idea to cast from a larger to a smaller type (say int -> short), I would like to add compiler flags (GCC) that make it an error (or at least a warning) to cast from larger to smaller types.

Are there flags to do this?

Edit: Yes, I am referring to implicit conversions. Thank you to the people who answered this question.

  • You want `short x = (short) 123456789;` to warn? OR is it OK for only `short x = /* no cast */ 123456789;` to warn? – chux - Reinstate Monica Sep 22 '22 at 17:16
  • 2
    A cast is an explicit operator in source code, a type in parentheses, like `(short)` in `x = (short) y;`. Some people use “cast” to mean any conversion, such as the automatic conversion that occurs in `short x = y;`. If you want a warning for implicit conversions, not casts, you should update your question to indicate that explicitly and not to use “cast” for that. If you want a warning for casts that narrow an integer type, that is not a warning compilers typically provide. Casts are commonly used to explicitly indicate a desired conversion, so they are not warned about. – Eric Postpischil Sep 22 '22 at 17:23

1 Answers1

2

If you mean:

short a; int b = 42; a = b;

-Wconversion is what you are looking for, -Werror=conversion to make it an error.

If you mean:

short a; int b = 42; a = (short)b;

You can check this answer:

By using an explicit conversion (a "cast"), you have told the compiler: "I definitely want to do this". That's what a cast means. It makes little sense for the compiler to then warn about it.

David Ranieri
  • 39,972
  • 7
  • 52
  • 94