Why does line feed in scanf () compile in C?

I recently wrote a simple program where I mistakenly used scanf () instead of printf () to display a message on the console. I expected to get a compile-time error, but it compiles without warnings and crashes at runtime. I know that scanf () is used to enter keyboard input. Should I get an error in the following program?

#include <stdio.h> int main() { scanf("Hello world"); // oops, It had to be printf() return 0; } 

Does it invoke undefined (UB) behavior? Is there any mention of this in the C standard? Why is it not checked at compile time whether valid and valid arguments were passed to scanf () or not?

+5
source share
4 answers

The code behaves correctly. Indeed, scanf declared

 int scanf(const char *format, ...); 

Fortunately, your format does not contain % , for which there would be no match in ... that would invoke UB.
In addition, format is a string literal that allows the compiler to go through it, ensuring that you pass the correct type of parameters with respect to format specifiers, since some health checks are included with higher levels of warnings. (-Wformat-family)

+6
source

Passing a string in scanf compiles fine because scanf expects a string as the first parameter. For a detailed description of scanf see the documentation or programming guide.

+6
source

The compiler cannot read your mind.

Both printf("Hello world") and scanf("Hello world") well formed.

+4
source

scanf accepts a string parameter . That's why it compiles fine, but it seems that your parameter is not as expected, so it crashes (or just exits) at runtime.

-1
source

All Articles