user17837290
user17837290

Reputation:

What are compiler flags to make type casting more strict in C?

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.

Upvotes: 2

Views: 725

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

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.

Upvotes: 3

Related Questions