Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

301
Visualizações
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?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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)

over 4 years ago · Santiago Trujillo Relatório

0

Passing a string to scanf compiles fine, because scanf expects a string as it first parameter. See the documentation or programming manual for detailed scanf description.

over 4 years ago · Santiago Trujillo Relatório

0

The compiler cannot read your mind.

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda