Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

c - printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

I have tried the following code:

wprintf(L"1 %s
","some string"); //Good
wprintf(L"2 %s
",L"some string"); //Not good -> print only first character of the string
printf("3 %s
","some string"); //Good
//printf("4 %s
",L"some string"); //Doesn't compile
printf("
");
wprintf(L"1 %S
","some string"); //Not good -> print some funny stuff
wprintf(L"2 %S
",L"some string"); //Good
//printf("3 %S
","some string"); //Doesn't compile
printf("4 %S
",L"some string");  //Good

And I get the following output:

1 some string
2 s
3 some string

1 g1 %s

2 some string
4 some string

So: it seems that both wprintf and printf are able to print correctly both a char* and a wchar*, but only if the exact specifier is used. If the wrong specifier is used, you might not get a compiling error (nor warning!) and end up with wrong behavior. Do you experience the same behaviour?

Note: This was tested under Windows, compiled with MinGW and g++ 4.7.2 (I will check gcc later)

Edit: I also tried %ls (result is in the comments)

printf("
");
wprintf(L"1 %ls
","some string"); //Not good -> print funny stuff
wprintf(L"2 %ls
",L"some string"); //Good
// printf("3 %ls
","some string"); //Doesn't compile
printf("4 %ls
",L"some string");  //Good
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suspect GCC (mingw) has custom code to disable the checks for the wide printf functions on Windows. This is because Microsoft's own implementation (MSVCRT) is badly wrong and has %s and %ls backwards for the wide printf functions; since GCC can't be sure whether you will be linking with MS's broken implementation or some corrected one, the least-obtrusive thing it can do is just shut off the warning.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...