Writing & Running Your First C Program
Anatomy of a C program: preprocessor directives, the main() entry point, statement terminators, return codes, and compiling from terminal.
- Every C program must contain exactly one
main()function. - Statements in C must end with a semicolon (
;). - Preprocessor directives begin with
#and do NOT end with a semicolon. - Comments in C are written with
//(single line) or/* ... */(multi-line). printf()outputs formatted text to stdout, defined in<stdio.h>.
Anatomy of a C Program
Let's dissect the standard C program line-by-line:
- 1`#include <stdio.h>`:
- The
#symbol designates a preprocessor directive. includeinstructs the preprocessor to paste the header filestdio.h(Standard Input/Output) into this file before compiling.stdio.hcontains the function declarations forprintf,scanf,getchar, and file operations.
- 2`int main(void)`:
- The execution entry point of every C program. The OS begins executing instructions from
main. intspecifies that this function returns an integer status code to the calling operating system shell.voidin the parameter list explicitly states thatmaintakes no arguments.
- 3Curly Braces `{ ... }`:
- Marks the start and end of a code block / function body.
- 4`printf(...);`:
- Calls the library function to format and print text to standard output.
\nis an escape character representing a newline.- The semicolon
;marks the termination of the statement.
- 5`return 0;`:
- Passes exit code
0back to the host operating system, which conventionally signifies successful execution without errors. Non-zero values indicate error states.
Unlike Python or JavaScript, C strictly requires semicolons after statements. Forgetting a semicolon is one of the most common syntax errors for beginners.
How to Compile & Run via Terminal
Save your code in a file named hello.c. Open your command prompt or bash terminal:
If you want the compiler to catch potential bugs and enforce strict ANSI/ISO standards, compile with helpful warning flags:
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 2 correct(0 attempted)
What does returning 0 from main() signal to the operating system?
BeginnerWhich header file is required to use printf() and scanf() in C?
Beginner