Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code snippet compile?

Tags:

c

Why does the following code compile?

#include <stdio.h>

int main(void) {
    getchar;
}
like image 553
missingfaktor Avatar asked Jan 08 '10 16:01

missingfaktor


People also ask

Why does code compile?

A compiler takes the recipe (code) for a new program (written in a high level language) and transforms this Code into a new language (Machine Language) that can be understood by the computer itself.

What is the purpose of this code snippet?

"Code Snippet" is a term used to describe a small portion of re-usable source code, machine code, or text. They allow a programmer to avoid typing repetitive code during the course of routine programming.

What does snippet of code mean?

Snippet is a programming term for a small region of re-usable source code, machine code, or text. Ordinarily, these are formally defined operative units to incorporate into larger programming modules.

What happens when you compile code?

A compiler takes the program code (source code) and converts the source code to a machine language module (called an object file). Another specialized program, called a linker, combines this object file with other previously compiled object files (in particular run-time modules) to create an executable file.


3 Answers

Because function names are aliases to function pointers to those functions, which are themselves values much like integers.. This is semantically very similar to

#include <stdio.h>

int main(void) {
    42;
}

It is valid but pointless.

like image 165
Alex Brown Avatar answered Sep 21 '22 20:09

Alex Brown


The same reason 1; would compile, getchar is just an address to a function. The result is evaluated, then discarded. In the language specification, it's called an "expression statement";

like image 32
eduffy Avatar answered Sep 23 '22 20:09

eduffy


C is weird, this code compiles too, but it segfaults which for the record, is the smallest segfault in C history.

main;
like image 39
graphitemaster Avatar answered Sep 23 '22 20:09

graphitemaster