Viva64 Send comments on this topic.
Find incorrect explicit type conversion

Glossary Item Box

The analyzer does not show the warnings connected with the type conversion in the case of explicit type conversion. But explicit type conversion can disguise the errors, e. g.:

  CopyCode image Copy Code
TCHAR *begin, *end;
// error:
int size = end - begin;
// no error here:
unsigned size = static_cast<unsigned>(end - begin);

Both the first and the second statements contains an error caused by the fact that with a 64-bit platform the array size can be more than 232 bites (4 Gb) and the result of the end – begin statement can’t fit the 32-bit data type. The only way out of the situation will be to use a memsize type for storing the result, e. g.:

  CopyCode image Copy Code
ptrdiff_t size = end - begin;

The problem is that the explicit type conversion disguises the error in the standard mode and the analyzer shows the warning only for int size = end - begin; line. The reasons for which no warnings are shown for explicit type conversion are the following:

  • very often explicit type conversion has some grounds for it, and the developer, while performing it, realizes possible consequences;
  • explicit type conversion can be used specially for suppression of the compiler’s or analyzer’s warnings.

You have a possibility to choose a mode of work, using which the explicit type conversion won’t suppress the analyzer’s warnings. In order to choose this mode see the Settings: Miscellaneous section.

The examples of explicit type conversion which will be found:

  CopyCode image Copy Code
size_t size;
int i32;
short i16;
...
size = (size_t)(i16 * i16 * i16);
i32 = static_cast<int>(sizeof(char));
for (i32 = 0; i32 != int(size); ++i) { ... }

The examples of explicit type conversion which won’t be found because they are incorrect:

  CopyCode image Copy Code
const int *constPtr;
...
int *ptr = const_cast<int *>(constPtr);
float f = float(constPtr[0]);
char ch = static_cast<char>(sizeof(double));

See also:

memsize type

implicit type conversion

explicit type conversion

Settings: Miscellaneous