Reputation: 23
I had an interview question where the interviewer asked me what error would we get from the below output:
int main()
{
printf("hello world");
return 0;
}
#include <stdio.h>
I answered "no error" and it will display the output.
can anyone help me with this???
Please note"the missing angular brackets is intentionally done by me so dont bother about that"
Upvotes: 2
Views: 143
Reputation: 146
There are two errors here. The first is that the include directive must happen before the code that requires that header information, in this case printf() is declared in stdio.h, and the second is that the filename in the include directive must be enclosed in angle brackets, <>, or quotes, "".
Upvotes: 0
Reputation: 263617
It depends on the compiler.
Most C compilers will probably accept that code (perhaps with a warning) and produce an executable that prints the expected output.
Under C90 rules, the behavior of the printf
call is undefined; it's invalid to call a variadic function with no visible prototype. Variadic functions can have a different calling convention from ordinary functions, and you have to let the compiler know that printf
is variadic so it can generate correct code for the call.
Under C99 and later rules, calling any function with no visible declaration (which may or may not be a prototype) is a constraint violation, requiring at least a compile-time warning.
The standard doesn't hint at what happens if you call printf
without the required prototype, but in practice most compilers will handle it "correctly".
The missing '\n'
at the end of the output means that the program's behavior is undefined if the implementation requires a newline at the end of the output; whether that's required or not is implementation-defined. In any case, adding a newline is a good idea.
The #include <stdio.h>
at the end of the source file should be useless but harmless.
I'm assuming that the source file actually contains #include <stdio.h>
and not #include stdio.h
; the latter would be a syntax error.
(Practically speaking, of course, the #include <stdio.h>
should be at the top. In a professional setting, the output is irrelevant, since the program will never survive a code review.)
Upvotes: 7
Reputation: 10620
When your main()
function is being declared, the compiler will run into the first line of main()
and it will have no idea what printf()
is. You will get an error about the compiler complaining about an undeclared function.
Assuming, of course, the missing <
and >
was a mistake introduced when you copied your question over.
Upvotes: 0
Reputation: 4421
You will get an error for missing quotes or <>
in the filename for the #include
. It should be:
#include <stdio.h>
Apart from that, it should compile with a warning about an implicit declaration to printf()
. On Clang, it gives me:
test.c:3:5: warning: implicitly declaring library function 'printf' with type 'int (const char *, ...)'
printf("hello world");
^
Upvotes: 1