Wednesday, October 5, 2022

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

Issue

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.


Solution

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.



Answered By - David Ranieri
Answer Checked By - Mildred Charles (WPSolving Admin)