%d vs %s

I declared a character array and at the time of taking input I used %d instead of %s in function scanf. Isnt my compiler suppose to flash an error for this? Or is it, due to some reason, not considered as compile time error ?
Anyone??
Last edited on
Or is it, due to some reason, not considered as compile time error

Correct. The compiler does NOT check for correspondence between a format string and arguments in a scanf statement. Even at run time, there is no type checking of arguments. Arguments are blindly interpreted per the format string.
GCC will warn you if you use the -Wformat flag (included by -Wall).

https://gcc.gnu.org/onlinedocs/gcc-4.9.1/gcc/Warning-Options.html#index-Wformat-294

1
2
3
4
5
6
7
8
9
#include <cstdio>

int main()
{
	char str[80];

	// warning: format ‘%d’ expects argument of type ‘int*’, but argument 2 has type ‘char*’
	std::scanf("%d", str); 
}
Last edited on
Registered users can post here. Sign in or register to post.