Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why passing string to scanf() compiles fine in C?

I recently wrote a simple program where I by mistake use scanf() instead of printf() for displaying a message on console. I was expecting to get compile time error, but it compiles fine without warnings & crashes at runtime. I know that scanf() is used for taking input from keyboard. Shouldn't I get an error in following program?

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

Is it invokes undefined behavior(UB)? Is there any mention about this in C standard? Why it isn't checked at compile time whether proper & valid arguments are passed to scanf() function or not?

like image 361
Destructor Avatar asked Jun 10 '15 16:06

Destructor


People also ask

What is the problem with scanf () to read a string?

Explanation: The problem with the above code is scanf() reads an integer and leaves a newline character in the buffer. So fgets() only reads newline and the string “test” is ignored by the program.

Can we use scanf for string in C?

We can take string input in C using scanf(“%s”, str). But, it accepts string only until it finds the first space. There are 4 methods by which the C program accepts a string with space in the form of user input.


1 Answers

The code is behaving correctly. Indeed, scanf is declared

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

Luckily, your format does not contain any % for which there would be no correspondence in ..., which would invoke UB.
Further, format is a string literal which allows the compiler to go through it ensuring you passed the right type of parameters in regards to the format specifiers, as part of sanity checks enabled with higher warning levels. (-Wformat family)

like image 128
edmz Avatar answered Oct 04 '22 01:10

edmz