Register

C for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

The parts of a C program

Starting out11 min readLesson 2 of 5

2.1 Functions hold the code

A C program is a collection of functions. Each function has a name, a parameter list, a return type, and a body inside braces. Execution starts at main and follows the calls you write.

A statement is one complete instruction, and it ends with a semicolon. printf("Hi\n"); and return 0; are statements. int total = 0; is a declaration, and it also ends with a semicolon.

#include <stdio.h> is a directive instead. It has no semicolon because the preprocessor owns the whole line. The line tells the preprocessor to paste the declarations from the standard input and output header into your file, so the compiler knows the argument types for printf.

c
#include <stdio.h>    /* declares printf */

int main(void)         /* execution starts here */
{
    printf("A program is a list of statements.\n");
    return 0;          /* status sent back to the system */
}

Output

A program is a list of statements.

2.2 Comments

Comments are notes for people, and the compiler ignores them.

  • /* ... */ covers everything between the markers, including several lines
  • // ... runs from the slashes to the end of the line, and C99 made it standard

Use a comment to record something the code cannot show, such as the meaning of a number or the reason for an unusual order of operations. A comment that repeats the statement beside it adds noise. int count = 0; // set count to zero tells the reader nothing new. int days = 365; // common year, leap days ignored records a decision.

Comments also help when you are learning: label the part of a program you are studying, then delete the label once you can read the code without it.

c
#include <stdio.h>

int main(void)
{
    /* A block comment can span
       more than one line. */
    int seconds = 60 * 60 * 24;  // seconds in a day
    printf("A day has %d seconds.\n", seconds);
    return 0;
}

Output

A day has 86400 seconds.

2.3 Printing text and numbers

printf takes a format string followed by values. The format string holds ordinary text and conversion specifications that begin with %. Each conversion specification reads the next argument and prints it in a chosen form.

  • %d prints an int
  • %f prints a double; %.2f keeps two digits after the decimal point
  • %c prints one char
  • %s prints a string of characters

The number and order of the arguments must match the specifications. A specification with no argument makes printf read whatever value sits next, and the printed result has no meaning. Compilers warn about an obvious mismatch when warnings are on.

A literal percent sign needs two characters: %% prints %.

c
#include <stdio.h>

int main(void)
{
    int apples = 4;
    double price = 1.25;

    printf("%d apples cost %.2f\n", apples, apples * price);
    printf("%s %c %d\n", "text", 'A', 7);
    return 0;
}

Output

4 apples cost 5.00
text A 7

2.4 Escape sequences

Some characters cannot be typed directly inside a string, and some are invisible. C writes them with a backslash, in an escape sequence.

  • \n moves to the next line
  • \t moves to the next tab stop
  • \\ prints one backslash
  • \" prints a double quote inside a string literal
  • \0 is the null character, which marks the end of a string

The sequence takes two characters in your source and produces one character in the output. A single string can hold several of them.

c
#include <stdio.h>

int main(void)
{
    printf("Name\tScore\n");
    printf("Ada\t95\n");
    printf("A quote: \"done\" and a backslash: \\\n");
    return 0;
}

Output

Name	Score
Ada	95
A quote: "done" and a backslash: \

2.5 Layout and white space

The compiler ignores most white space. Indentation, blank lines, and the position of braces do not change what the program does. They change how quickly a person can read it.

Two brace styles are common. One keeps the opening brace on the same line as if. The other puts it on a line of its own. Both compile. Pick one, use it in every file, and indent the body by the same amount each time.

When you read an unfamiliar program, find main first, then read from its first statement to the last and follow each function call as a detour.

2.6 Putting the pieces together

A C file usually reads in this order: directives, prototypes for functions defined later, main, then the other function definitions. The order matters for names the compiler has not seen yet, and the functions lesson explains why.

A short program that does one thing clearly is easier to extend than a long one that mixes input, calculation, and printing in one block.

c
#include <stdio.h>

int main(void)
{
    int quantity = 3;
    double unit = 2.50;

    printf("Item\tQty\tTotal\n");
    printf("Pen\t%d\t%.2f\n", quantity, quantity * unit);
    return 0;
}

Output

Item	Qty	Total
Pen	3	7.50

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01Why does `#include <stdio.h>` not need a semicolon?

    It is a preprocessor directive, and the preprocessor ends a directive at the newline. A semicolon there is an extra token, and some compilers warn about it.

  • 02What is the difference between `%d` and `%f`?

    `%d` prints an `int` as a decimal number. `%f` prints a `double` with six digits after the decimal point by default, and `%.2f` limits it to two.

  • 03What happens when a format specifier does not match its argument?

    `printf` trusts the format string. A `%d` given a `double` prints a meaningless number, and a missing argument makes it read an unrelated value. Warnings catch the obvious cases.