Chapter 02 of 24
2. Your first program
Build a program one line at a time
A C program needs a starting point. That starting point is a function named main. Begin with the smallest useful shape: include the declaration for the library feature you need, define main, put instructions between braces, and return a status when the work is done.
#include <stdio.h>lets the compiler know about standard printing functions.puts("Hello!");asks the library to display text followed by a new line.return 0;tells the environment that the program completed successfully.
Change one part, compile, and run again. This small edit-build-run cycle makes it easier to connect each line you write to what the computer does.
Create hello.c:
#include <stdio.h>
int main(void)
{
puts("Hello, world!");
return 0;
}
#include <stdio.h>makes declarations for standard input/output available.int main(void)defines the program's entry point.voidmeans it takes no
arguments.- Braces
{}group a function body. putsprints a line of text.return 0;reports successful completion to the environment.- C statements usually end with a semicolon.
Try changing the message, printing two lines, and compiling after each change.
Then deliberately remove a semicolon and read the compiler's diagnostic.
Reading the program from top to bottom
The #include line is a preprocessing directive, not a C statement, so it
does not end with a semicolon. It makes the declaration of puts available
to the compiler. The function definition begins at int main(void) and its
body is between braces. The call puts("Hello, world!"); passes a string
literal to a library function. The return statement ends main and supplies
an exit status.
Whitespace and indentation usually do not change the meaning of C, but
consistent indentation makes nested code easier to read. A comment starts
with /* and ends with */; C99 and later also support // to the end of a
line. Comments explain intent, not the obvious syntax:
int main(void)
{
int value = 5;
// The input has already been checked before this calculation.
int doubled = value * 2;
return doubled == 10 ? 0 : 1;
}
Compiler messages give a file, line, and often a nearby location. The
reported line may be where the compiler noticed a problem, not where it began.
Fix the first meaningful error, rebuild, and then inspect later messages;
one missing brace can create many follow-on errors.
Checkpoint: Add a comment, print two separate lines, and explain why the
include line has no semicolon.
Exercises: print your name; print a three-line greeting; explain each line
of the example in your own words.