See this example:
FILE* f = NULL; // MSVC warns if I do not initialize them.
char* s = NULL;
s = f; // these two lines compiles in .c file but not in .cpp file
f = s; // this is really dangerous!
I found this bug (or, maybe it is a feature in MSVC?), because several hours ago, I wrote something like this:
fread(f, 1, size, str); // crash! exchange f and str!
which compiles without any warning, let alone errors, and crashes my program until I change the file extension to .cpp.
Why doesn't MSVC perform such a basic check in .c files?
CodePudding user response:
MSVS does warn you (https://godbolt.org/z/e5oq7fexM):
<source>(16): warning C4133: '=': incompatible types - from 'FILE *' to 'char *'
<source>(17): warning C4133: '=': incompatible types - from 'char *' to 'FILE *'
Why doesn't MSVC perform such a basic checks .c files?
It does, you probably have disabled all the warnings.
these two lines compiles in .c file but not in .cpp file
Because C
& C
are different languages. C
allows implicit pointer conversions, C
does not. It is why you need to cast the result of malloc
in C
, but you do not in C
You can use -WX
option to treat warnings as errors and your program will not compile anymore https://godbolt.org/z/GvssPbxEv
<source>(10): error C2220: the following warning is treated as an error
<source>(10): warning C4133: '=': incompatible types - from 'FILE *' to 'char *'
<source>(11): warning C4133: '=': incompatible types - from 'char *' to 'FILE *'
You can learn more about MSVC options here: https://learn.microsoft.com/en-us/cpp/build/reference/compiler-option-warning-level?view=msvc-170