jojy joseph
jojy joseph

Reputation: 49

How can we disable implicit casting in MSVC C++?

I am working on an embedded project. When I compile my solution in the embedded tool chain, it gives me errors related to implicit conversion as it's not supported.

I have an equivalent desktop application on MSVC. I wish to replicate the same situation in MSVC solution. But the MSVC by default is able to do implicit conversion.

Is there a way to disable implicit conversion in MSVC?

Upvotes: 1

Views: 1182

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51825

For conversions such as double to int, where you would normally get:

warning C4244: '=': conversion from 'double' to 'int', possible loss of data

you can 'convert' this warning to an error, using:

#pragma warning(error:4244)

Thus, the following code will fail to compile:

#pragma warning(error:4244)
double foo;
int bar;
bar = foo;

error C4244: '=': conversion from 'double' to 'int', possible loss of data

There are similar warnings for other implicit conversions, which can be converted to errors in the same way. For, example, conversions between signed and unsigned integer types elicit warning number 4365.

Note: You would also need the warning level set to at least /W4, in order for the warnings to show. Alternatively, if you don't want to be bothered by all the 'extra' warnings this may generate, you can explicitly enable any selected warning with: #pragma warning(enable:4244). (I would recommend the former, especially when building for an embedded platform.)

Upvotes: 1

Related Questions