C, lesson 1
C is a small, fast language that sits close to the machine. Operating systems, databases and the interpreters of many other languages are written in it. A C program is plain text that a compiler (here GCC 15) turns into machine code before it runs. If the compiler finds a mistake, nothing runs at all: you get an error message instead.
Here is the smallest useful C program:
Line by line:
#include <stdio.h> pulls in the declarations for the standard input/output functions,
such as printf. Without it the compiler does not know what printf is.int main(void) is where every C program starts. void means it takes no arguments, and
int means it hands a whole number back to the operating system when it finishes.{ } hold the body of the function.2 exercises to try what you just read.
;.return 0; reports success. Any other number usually signals an error. In main you may
leave it out and C returns 0 for you, but writing it makes the intent clear.printf ("print formatted") writes text to standard output. Unlike print in some other
languages, it does not add a line break for you. You ask for one with the escape sequence
\n:
A few other escape sequences you will use:
| Sequence | Meaning |
|---|---|
\n | new line |
\t | tab |
\" | a double quote inside a string |
\\ | a single backslash |
If you just want to print a fixed line, puts is simpler: it prints the string and then adds a
new line by itself.
Comments are notes for humans. The compiler throws them away. C has two styles:
When you press Run, two things happen. First the compiler reads the whole file, checks it,
and produces an executable. Then that executable runs, starting at the first line inside
main and going down one statement at a time. Because compiling comes first, a typo on the
last line stops the whole program from starting, even if the earlier lines are fine. Read
compiler errors from the top: the first error is usually the real one, and the ones after it
are often side effects.
Write a program that prints exactly these two lines:
The program reads no input.
Print this sign exactly. The gap between the item and the price is a single tab character,
and the quotes around Daily are real double quotes:
Use escape sequences: \" for the quotes, \t for the tabs and \\ for the backslash. The
program reads no input.
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
return 0;
}printf("one ");
printf("line\n"); // prints: one line
printf("two\nlines\n");puts("Ready."); // same as printf("Ready.\n");// A line comment runs to the end of the line.
/* A block comment can
span several lines. */
printf("Hi\n"); /* or sit next to code */Hello, World!
I am learning C."Daily" menu
Coffee 2.50
Tea 1.80
Path: C:\menu