08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4 ■ Programs with Selection Logic

In C, we use the #define directive to define symbolic constants, among other uses. We show

how by rewriting Program P4.1 as Program P4.6.

Program P4.6

//This program illustrates the use of symbolic constants

//Print job charge based on hours worked and cost of parts

#include <stdio.h>

#define ChargePerHour 100

#define MinJobCost 150

int main() {

double hours, parts, jobCharge;

printf("Hours worked? ");

scanf("%lf", &hours);

printf("Cost of parts? ");

scanf("%lf", &parts);

jobCharge = hours * ChargePerHour + parts;

if (jobCharge < MinJobCost) jobCharge = MinJobCost;

printf("\nCharge for the job: $%3.2f\n", jobCharge);

}

4.6.1 The #define Directive

Directives in C normally come at the top of the program. For our purposes, the #define directive

takes the following form:

#define identifier followed by the "replacement text"

In the program, we used

#define ChargePerHour 100

Note that this is not a normal C statement and a semicolon is not needed to end it. Here, the

identifier is ChargePerHour and the replacement text is the constant 100. In the body of the

program, we use the identifier instead of the constant.

When the program is compiled, C performs what is called a “pre-processing” step. It

replaces all occurrences of the identifier by its replacement text. In program P4.6, it replaces all

occurrences of ChargePerHour by 100 and all occurrences of MinJobCost by 150 . After this is

done, the program is compiled. It is up to the programmer to ensure that, when the identifier is

replaced, the resulting statement makes sense.

Effectively, the directives say that the identifier ChargePerHour is equivalent to the constant

100 and the identifier MinJobCost is equivalent to 150.

81

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!