munotes®

The Structure of a C Program

Chapter Four

Syllabus topic 1, "Introduction: Algorithms, History of C, Structure of C Program. Program Characteristics, Compiler, Linker and preprocessor, pseudo code statements and flowchart symbols, Desirable program characteristics. Program structure. Compilation and Execution of a Program, C Character Set, identifiers and keywords, data types and sizes, constants and its types, variables, Character and character strings, typedef, typecasting"

Pages 14 to 18 of 222

In one line

A C program is a file of text made of preprocessor directives and function definitions, exactly one of which must be a function called main, and execution starts at the first statement inside main and stops when main returns.

Why a program has a fixed shape at all

A compiler is not a reader. It cannot tell from the sense of what you wrote where your program begins, so the language fixes that in advance: the starting point is always the function named main. Nothing else will do, and no other name works, however sensible.

The same is true of everything else in the shape. A name must be declared before it is used, because the compiler reads your file once from top to bottom and cannot know what is coming. A statement ends with a semicolon, because a newline in C means nothing at all and something has to mark the end. Every rule in this chapter exists because a program has to be read by a machine that does not guess.

The smallest complete C program that does something

#include <stdio.h>

int main(void)
{
    printf("This program did one thing and stopped.\n");
    return 0;
}

Compiled and run, it prints:

This program did one thing and stopped.

Six lines, and every part of the language's required shape is in them. Read them one at a time.

#include <stdio.h> is a preprocessor directive. A line beginning with # is not a C statement at all. It is an instruction to a program that runs before the compiler, and this one says: find the file stdio.h and paste its contents in here. stdio.h is the standard input and output header, and it is what tells the compiler that a function called printf exists and what kind of arguments it takes. Without it the program does not compile cleanly. Chapter 22 is the preprocessor in full.

int main(void) is a function definition header, and it says three things. main is the name, and it is the one name the language reserves for the starting point. (void) says the function takes no arguments. int says it gives back an integer when it finishes, and the operating system reads that integer to find out whether the program worked.

{ and } are braces, and together they make a block: the body of the function. Everything the function does sits between them.

printf("This program did one thing and stopped.\n"); is a statement, which is one complete instruction. It calls a library function to write text to the screen. The \n inside the quotation marks is one character, the newline, and it is what moves the cursor to the next line. The semicolon at the end is part of the statement, not decoration.

munotes.in14

The Structure of a C Program

return 0; ends main and hands the integer 0 back. By long convention 0 means the program succeeded and anything else means it failed.

The six sections MU's answer wants

Written out in full, a C program can have six sections in this order. The smallest program above has only two of them, which is the point: four of the six are optional and two are not.

SectionWhat goes in itRequired?
Documentation sectionComments saying what the file is, who wrote it and whenNo
Link section#include directives, which bring in headersIn practice, yes
Definition section#define directives, which name constantsNo
Global declaration sectionVariables and function declarations visible to the whole fileNo
The main functionThe block execution starts inYes, always
Subprogram sectionThe other functions the program is made ofNo

Only main is compulsory as a matter of language. The link section is listed as required in practice because a program that prints anything needs stdio.h, and a program that needs nothing from the library needs no header at all.

A program with all six sections in it

This is the same simple interest calculation the lab asks for in its very first practical, written so that each of the six sections is present and labelled.

/*
 * simple-interest.c
 * Simple interest on a deposit, with the calculation in its own function.
 * Documentation section: this comment, and nothing else.
 */

#include <stdio.h>             /* link section */

#define PERCENT 100.0          /* definition section */

double interest(double principal, double rate, double years);
int calls = 0;                 /* global declaration section */

int main(void)                 /* the main function */
{
    double si = interest(15000.0, 8.5, 2.0);

    printf("Simple interest: %.2f\n", si);
    printf("Function calls : %d\n", calls);
    return 0;
}

double interest(double principal, double rate, double years)
{                              /* subprogram section */
    calls = calls + 1;
    return principal * rate * years / PERCENT;
}
Simple interest: 2550.00
Function calls : 1

Four things in that file are worth naming now and learning later.

  • / ... / is a comment. The compiler deletes it. It is for the person reading the file, and a comment may run over as many lines as you like.
  • #define PERCENT 100.0 makes the preprocessor replace the word PERCENT with 100.0 everywhere below it. It is not a variable. Chapter 22.
  • double interest(double principal, double rate, double years); with a semicolon and no body is a function declaration, also called a prototype. It promises the compiler that such a function exists further down, so that main can call it before the compiler has read it. Chapter 32.
  • int calls = 0; outside any function is a global variable, reachable from every function in the file. Chapter 21 says why you should nearly always prefer one that is not.
munotes.in15

The Structure of a C Program

Move the definition of interest above main and the declaration becomes unnecessary, because the compiler will have read the real thing by the time it reaches the call. Both arrangements are correct. The declaration is the one that keeps working when the program grows into more than one file.

The rules that are not negotiable

  1. There is exactly one main. No main and the linker fails with an undefined reference. Two and it fails with a duplicate symbol.
  2. C is case sensitive. main, Main and MAIN are three different names, and only the first is the starting point.
  3. Every statement ends with a semicolon. A function definition header and a preprocessor directive do not, and those are the two places beginners put one.
  4. Braces come in pairs, and each { needs its }.
  5. A name must be declared before it is used. The compiler reads the file once, downwards.
  6. A preprocessor directive occupies its own line and begins with #.

What the structure does NOT mean

A newline does not end a statement. C ignores where you press Return. The whole of the first program can be written on one line and it compiles to exactly the same thing. Indentation and line breaks are for the reader, and they are worth a great deal, but the compiler is not reading them.

main is not called by your program. It is called for you when the program starts, by code the linker puts in. This is why nothing in the file appears to call it.

#include <stdio.h> does not make the program bigger by including a library. The header is a text file of declarations. It tells the compiler what printf looks like; the machine code for printf is joined on later by the linker, which is chapter 5.

return 0; is not what prints the output. It is the value handed back to whatever started the program. Leaving it out of main is legal in C99 and later, where reaching the closing brace of main returns 0 anyway, but write it: it says plainly what you meant, and in every function other than main leaving it out is a real bug.

The six sections are not six blocks of a form. They are the places things may go, in order. A real file usually has three of them.

Quick revision

  • A C program is preprocessor directives plus function definitions.
  • Exactly one function must be called main. Execution starts there.
  • int main(void) returns an int and takes no arguments; 0 means success.
  • #include is a directive to the preprocessor, not a C statement, and takes no semicolon.
  • A header such as stdio.h supplies declarations, not machine code.
  • Six sections, in order: documentation, link, definition, global declaration, main, subprogram. Only main is compulsory.
  • Statements end with a semicolon. Braces delimit a block. C is case sensitive.
  • A name must be declared before it is used, which is why prototypes exist.
munotes.in16

The Structure of a C Program

Test yourself

1. Write the smallest C program that compiles, runs and prints nothing.

int main(void)
{
    return 0;
}

It prints nothing at all, so the output block beside it is empty:

It needs no header, because it uses nothing from the library. It compiles clean under -Wall -Wextra and exits with status 0.

2. Name the six sections of a C program in order, and say which are compulsory.

Documentation, link, definition, global declaration, main, subprogram. Only main is compulsory; in practice the link section is present in any program that does input or output.

3. Why must printf be declared before it is used, and where does that declaration come from?

Because the compiler reads the file once and must know the function's return type and parameter types to compile the call correctly. The declaration comes from stdio.h, pasted in by the preprocessor.

4. What is wrong with this?

#include <stdio.h>;

void main(void)
{
    printf("hello\n")
}

Three errors. The directive has a semicolon it must not have. main is declared void, and the standard requires int. The printf statement has no semicolon.

5. Does a comment cost anything at run time?

No. The preprocessor removes comments before the compiler sees the file, so they are not in the finished program at all.

What can be asked on this, and how to answer it

"Explain the structure of a C program." Give the six sections in order with one line each, then draw or write out a short program with the sections labelled, exactly as this chapter does. Say which are compulsory. An answer that lists the six and shows no program is half an answer, and this is the commonest form of the question on this paper.

"What is the purpose of main()?" It is the function where execution begins, and the one function every C program must have. Its return value is reported to the operating system, and 0 conventionally means success.

"What is the use of #include <stdio.h>?" It tells the preprocessor to insert the standard input and output header, which declares the library functions for input and output, printf and scanf among them, so the compiler can check your calls to them.

munotes.in17

The Structure of a C Program

"Distinguish between a declaration and a definition of a function." A declaration gives the name, the return type and the parameter types and ends in a semicolon; it promises the function exists. A definition gives all of that and the body in braces; it is the function. A file may declare a function many times and must define it once.

"Is void main() correct?" Not in standard C. The standard gives main a return type of int. Some older compilers accept void main(), which is exactly why students write it, and it should not be written.

munotes.in18

The rest of this subject

These notes are cut from the University's printed syllabus. Open the syllabus itself for the same subject.

Report or request
Done!