Home > Articles > Programming > C/C++

This chapter is from the book

The Program’s Components

The following sections describe the various components of the preceding sample program. Line numbers are included so that you can easily identify the program parts discussed.

The main() Function (Lines 9 Through 23)

The only component required in every executable C program is the main() function. In its simplest form, the main() function consists of the name main followed by a pair of parentheses containing the word void ((void)) and a pair of braces ({}). You can leave the word void out and the program still works with most compilers. The ANSI Standard states that you should include the word void so that you know there is nothing sent to the main function.

Within the braces are statements that make up the main body of the program. Under normal circumstances, program execution starts at the first statement in main() and terminates at the last statement in main(). Per the ANSI Standard, the only statement that you need to include in this example is the return statement on line 22.

The #include and #define Directives (Lines 2 and 3)

The #include directive instructs the C compiler to add the contents of an include file into your program during compilation. An include file is a separate disk file that contains information that can be used by your program or the compiler. Several of these files (sometimes called header files) are supplied with your compiler. You rarely need to modify the information in these files; that’s why they’re kept separate from your source code. Include files should all have an .h extension (for example, stdio.h).

You use the #include directive to instruct the compiler to add a specific include file to your program during compilation. In Listing 2.1, the #include directive is interpreted to mean “Add the contents of the file stdio.h.” You will almost always include one or more include files in your C programs. Lesson 22, “Advanced Compiler Use” presents more information about include files.

The #define directive instructs the C compiler to replace a specific term with its assigned value throughout your program. By setting a variable at the top of your program and then using the term throughout the code, you can more easily change a term if needed by changing the single #define line as opposed to every place throughout the code. For example, if you wrote a payroll program that used a specific deduction for health insurance and the insurance rate changed, tweaking a variable created with #define named HEALTH_INSURANCE at the top of your program (or in a header file) would be so much easier than searching through lines and lines of code looking for every instance that had the information. Lesson 3, “Storing Information: Variables and Constants” covers the #define directive.

The Variable Definition (Line 5)

A variable is a name assigned to a location in memory used to store information. Your program uses variables to store various kinds of information during program execution. In C, a variable must be defined before it can be used. A variable definition informs the compiler of the variable’s name and the type of information the variable is to hold. In the sample program, the definition on line 4, int year1, year2;, defines two variables—named year1 and year2—that each hold an integer value. Lesson 3 presents more information about variables and variable definitions.

The Function Prototype (Line 7)

A function prototype provides the C compiler with the name and arguments of the functions contained in the program. It appears before the function is used. A function prototype is distinct from a function definition, which contains the actual statements that make up the function. (Function definitions are discussed in more detail in “The Function Definition” section.)

Program Statements (Lines 12, 13, 14, 17, 19, 20, 22, and 28)

The real work of a C program is done by its statements. C statements display information onscreen, read keyboard input, perform mathematical operations, call functions, read disk files, and all the other operations that a program needs to perform. Most of this book is devoted to teaching you the various C statements. For now, remember that in your source code, C statements are generally written one per line and always end with a semicolon. The statements in bigyear.c are explained briefly in the following sections.

The printf() Statement

The printf() statement (lines 12, 13, 19, and 20) is a library function that displays information onscreen. The printf() statement can display a simple text message (as in lines 12 and 13) or a message mixed with the value of one or more program variables (as in lines 19-20).

The scanf() Statement

The scanf() statement (line 14) is another library function. It reads data from the keyboard and assigns that data to one or more program variables.

The program statement on line 17 calls the function named calcYear(). In other words, it executes the program statements contained in the function calcYear(). It also sends the argument year1 to the function. After the statements in calcYear() are completed, calcYear() returns a value to the program. This value is stored in the variable named year2.

The return Statement

Lines 22 and 28 contain return statements. The return statement on line 28 is part of the function calcYear(). It calculates the year a person would be a specific age by adding the #define constant TARGET_AGE to the variable year1 and returns the result to the program that called calcYear(). The return statement on line 22 returns a value of 0 to the operating system just before the program ends.

The Function Definition (Lines 26 Through 29)

When defining functions before presenting the program bigyear.c, two types of functions—library functions and user-defined functions—were mentioned. The printf() and scanf() statements are examples of the first category, and the function named calcYear(), on lines 26 through 29, is a user-defined function. As the name implies, user-defined functions are written by the programmer during program development. This function adds the value of a created constant to a year and returns the answer (a different year) to the program that called it. In Lesson 5, “Packaging Code in Functions,” you learn that the proper use of functions is an important part of good C programming practice.

Note that in a real C program, you probably wouldn’t use a function for a task as simple as adding two numbers. It has been done here for demonstration purposes only.

Program Comments (Lines 1, 11, 16, and 25)

Any part of your program that starts with /* and ends with */ or any single line that begins with // is called a comment. The compiler ignores all comments, so they have absolutely no effect on how a program works. You can put anything you want into a comment, and it won’t modify the way your program operates. The first type of comment can span part of a line, an entire line, or multiple lines. Here are three examples:

/* A single-line comment */

int a,b,c; /* A partial-line comment */

/* a comment
spanning
multiple lines */

You should not use nested comments. A nested comment is a comment that has been put into another comment. Most compilers will not accept the following:

/*
/* Nested comment */
*/

Some compilers do allow nested comments. Although this feature might be tempting to use, you should avoid doing so. Because one of the benefits of C is portability, using a feature such as nested comments might limit the portability of your code. Nested comments also might lead to hard-to-find problems.

The second style of comment, the ones beginning with two consecutive forward slashes (//), are only for single-line comments. The two forward slashes tell the compiler to ignore everything that follows to the end of the line.

// This entire line is a comment
int x; // Comment starts with slashes

Many beginning programmers view program comments as unnecessary and a waste of time. This is a mistake! The operation of your program might be quite clear when you write the code; however, as your programs become larger and more complex, or when you need to modify a program you wrote 6 months ago, comments are invaluable. Now is the time to develop the habit of using comments liberally to document all your programming structures and operations. You can use either style of comments you prefer. Both are used throughout the programs in the book.

Using Braces (Lines 10, 23, 27, and 29)

You use braces {} to enclose the program lines that make up every C function—including the main() function. A group of one or more statements enclosed within braces is called a block. As you see in later lessons, C has many uses for blocks.

Running the Program

Take the time to enter, compile, and run bigyear.c. It provides additional practice in using your editor and compiler. Recall these steps from Lesson 1, “Getting Started with C”:

  1. Make your programming directory current.
  2. Start your editor.
  3. Enter the source code for bigyear.c exactly as shown in Listing 2.1, but be sure to omit the line numbers and colons.
  4. Save the program file.
  5. Compile and link the program by entering the appropriate command(s) for your compiler. If no error messages display, you can run the program by clicking the appropriate button in your C environment.
  6. If any error messages display, return to step 2 and correct the errors.

A Note on Accuracy

A computer is fast and accurate, but it also is completely literal. It doesn’t know enough to correct your simplest mistake; it takes everything you enter exactly as you entered it, not as you meant it!

This goes for your C source code as well. A simple typographical error in your program can cause the C compiler to choke, gag, and collapse. Fortunately, although the compiler isn’t smart enough to correct your errors (and you’ll make errors—everyone does!), it is smart enough to recognize them as errors and report them to you. (You saw in Lesson 1 how the compiler reports error messages and how you interpret them.)

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020