0% found this document useful (0 votes)
6 views20 pages

Chapter 1 - Computer Programming

Chapter One introduces programming, defining computers as devices that process data and solve problems through instructions known as programs. It discusses the evolution of programming languages from low-level binary and assembly languages to high-level languages, emphasizing the importance of algorithms and problem-solving techniques. The chapter also covers software development methodologies, including requirements specification and the use of tools like pseudocode, structured charts, and flowcharts to document program logic.

Uploaded by

soradida322
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views20 pages

Chapter 1 - Computer Programming

Chapter One introduces programming, defining computers as devices that process data and solve problems through instructions known as programs. It discusses the evolution of programming languages from low-level binary and assembly languages to high-level languages, emphasizing the importance of algorithms and problem-solving techniques. The chapter also covers software development methodologies, including requirements specification and the use of tools like pseudocode, structured charts, and flowcharts to document program logic.

Uploaded by

soradida322
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter One

1.1 Introduction to programming

A Computer is an electronic device that accepts data, performs computations, and makes logical
decisions according to instructions that have been given to it; then produces meaningful information
in a form that is useful to the user. In current world we live in, computers are almost used in all walks
of life for different purposes. They have been deployed to solve different real-life problems, from the
simplest game playing up to the complex nuclear energy production. Computers are important and
widely used in our society because they are cost-effective aids to problem solving in business,
government, industry, education, etc.
In order to solve a given problem, computers must be given the correct instruction about how they
can solve it. The terms computer programs, software programs, or just programs are the
instructions that tells the computer what to do. Computer requires programs to function, and a
computer program does nothing unless its instructions are executed by a CPU. Computer
programming (often shortened to programming or coding) is the process of writing, testing,
debugging/troubleshooting, and maintaining the source code of computer programs. Writing
computer programs means writing instructions, that will make the computer follow and run a program
based on those instructions. Each instruction is relatively simple, yet because of the computer's speed,
it is able to run millions of instructions in a second. A computer program usually consists of two
elements:
• Data – characteristics
• Code – action
Computer programs (source code) are often written by professionals known as Computer
Programmers (simply programmers) which are written in one of programming languages. A
programming language is an artificial language that can be used to control the behavior of a
machine, particularly a computer. Programming languages, like natural language (such as Amharic),
are defined by syntactic and semantic rules which describe their structure and meaning respectively.
▪ The syntax of a language describes the possible combinations of symbols that form a
syntactically correct program.

1
▪ The meaning given to a combination of symbols is handled by semantics. Many programming
languages have some form of written specification of their syntax and semantics; some are
defined only by an official implementation.
▪ In general, programming languages allow humans to communicate instructions to machines.
A main purpose of programming languages is to provide instructions to a computer. As such,
programming languages differ from most other forms of human expression in that they require a
greater degree of precision and completeness. When using a natural language to communicate with
other people, human authors and speakers can be ambiguous and make small errors, and still expect
their intent to be understood. However, computers do exactly what they are told to do, and cannot
understand the code the programmer "intended" to write. So, computers need to be instructed to
perform all the tasks. The combination of the language definition, the program, and the program's
inputs must fully specify the external behavior that occurs when the program is executed. Computer
languages have relatively few, exactly defined, rules for composition of programs, and strictly
controlled vocabularies in which unknown words must be defined before they can be used.

Available programming languages come in a variety of forms and types. Thousands of different
programming languages have been developed, used, and discarded. Programming languages can be
divided in to two major categories: low-level and high-level languages.

Low-level languages
Computers only understand one language and that is binary language or the language of 1s and 0s.
Binary language is also known as machine language, one of low-level languages. In the initial years
of computer programming, all the instructions were given in binary form. Although the computer
easily understood these programs, it proved too difficult for a normal human being to remember all
the instructions in the form of 0s and 1s. Therefore, computers remained mystery to a common person
until other languages such as assembly language was developed, which were easier to learn and
understand. Assembly language correspondences symbolic instructions and executable machine
codes and was created to use letters (called mnemonics) to each machine language instructions to
make it easier to remember or write. For example:
ADD A, B – adds two numbers in memory location A and B
Assembly language is nothing more than a symbolic representation of machine code, which allows
symbolic designation of memory locations. However, no matter how close assembly language is to
machine code, computers still cannot understand it. The assembly language must be translated to
machine code by a separate program called assembler. The machine instruction created by the
assembler from the original program (source code) is called object code. Thus, assembly languages

2
are unique to a specific computer (machine). Assemblers are written for each unique machine
language.
High-level languages
Although programming in assembly language is not as difficult and error prone as stringing together
ones and zeros, it is slow and cumbersome. In addition, it is hardware specific. The lack of portability
between different computers led to the development of high-level languages so called because they
permitted a programmer to ignore many low-level details of the computer's hardware. Further, it was
recognized that the closer the syntax, rules, and mnemonics of the programming language could be
to "natural language" the less likely it became that the programmer would inadvertently introduce
errors (called "bugs") into the program. High-level languages are more English-like and, therefore,
make it easier for programmers to "think" in the programming language. High-level languages also
require translation to machine language before execution. This translation is accomplished by either
a compiler or an interpreter. Compilers translate the entire source code program before execution.
Interpreters translate source code programs one line at a time. Interpreters are more interactive than
compilers. FORTRAN (FORmula TRANslator), BASIC (Bingers All Purpose Symbolic Instruction
Code), PASCAL, C, C++, Java are some examples of high-level languages.
The question of which language is best is one that consumes a lot of time and energy among computer
professionals. Every language has its strengths and weaknesses. For example, FORTRAN is a
particularly good language for processing numerical data, but it does not lend itself very well to
organizing large programs. Pascal is very good for writing well-structured and readable programs,
but it is not as flexible as the C programming language. C++ embodies powerful object-oriented
features
As might be expected in a dynamic and evolving field, there is no single standard for classifying
programming languages. Another most fundamental ways programming languages are characterized
(categorized) is by programming paradigm.
A programming paradigm provides the programmer's view of code execution. The most influential
paradigms are examined in the next three sections, in approximate chronological order.
Procedural Programming Languages
Procedural programming specifies a list of operations that the program must complete to reach the
desired state. Each program has a starting state, a list of operations to complete, and an ending point.

3
This approach is also known as imperative programming. Integral to the idea of procedural
programming is the concept of a procedure call.
Procedures, also known as functions, subroutines, or methods, are small sections of code that perform
a particular function. A procedure is effectively a list of computations to be carried out. Procedural
programming can be compared to unstructured programming, where all of the code resides in a single
large block. By splitting the programmatic tasks into small pieces, procedural programming allows a
section of code to be re-used in the program without making multiple copies. It also makes it easier
for programmers to understand and maintain program structure.
Two of the most popular procedural programming languages are FORTRAN and BASIC.
Structured Programming Languages
Structured programming is a special type of procedural programming. It provides additional tools to
manage the problems that larger programs were creating. Structured programming requires that
programmers break program structure into small pieces of code that are easily understood. It also
frowns upon the use of global variables and instead uses variables local to each subroutine. One of
the well-known features of structural programming is that it does not allow the use of the GOTO
statement. It is often associated with a "top-down" approach to design. The top-down approach begins
with an initial overview of the system that contains minimal details about the different parts.
Subsequent design iterations then add increasing detail to the components until the design is complete.
The most popular structured programming languages include C, Ada, and Pascal.
Object-Oriented Programming Languages
Object-oriented programming is one the newest and most powerful paradigms. In object- oriented
programs, the designer specifies both the data structures and the types of operations that can be
applied to those data structures. This pairing of a piece of data with the operations that can be
performed on it is known as an object. A program thus becomes a collection of cooperating objects,
rather than a list of instructions. Objects can store state information and interact with other objects,
but generally each object has a distinct, limited role.

1.2 Problem solving Techniques


Computer solves varieties of problems that can be expressed in a finite number of steps leading to a
precisely defined goal by writing different programs. A program is not needed only to solve a problem

4
but also it should be reliable, (maintainable) portable and efficient. In computer programming two
facts are given more weight:
• The first part focuses on defining the problem and logical procedures to follow in solving it.
• The second introduces the means by which programmers communicate those procedures to
the computer system so that it can be executed.
There are system analysis and design tools, particularly flowchart and structure chart, that can be used
to define the problem in terms of the steps to its solution. The programmer uses programming
language to communicate the logic of the solution to the computer.
Before a program is written, the programmer must clearly understand what data are to be used, the
desired result, and the procedure to be used to produce the result. The procedure, or solution, selected
is referred to as an algorithm.
An algorithm is defined as a step-by-step sequence of instructions that must terminate and describe
how the data is to be processed to produce the desired outputs. Simply, algorithm is a sequence of
instructions. Algorithms are a fundamental part of computing.
▪ An algorithm must satisfy the following requirements:
• Unambiguousness: It must not be ambiguous. In most cases we develop an algorithm
so that it can be translated into a program to be executed by computers. Computers
cannot cope with ambiguities. Therefore, every step in an algorithm must be clear as
to what it is supposed to do and how many times it is expected to be executed.
• Generality: It must have generality. A procedure that prints the message "One inch is
2.54 centimeters" is not an algorithm; however, one that converts a supplied number
of inches to centimeters is an algorithm.
• Correctness: It must be correct and must solve the problem for which it is designed.
• Finiteness: It must execute its steps and terminate in finite time. An algorithm that
never terminates is unacceptable.
✓ In general, algorithms have input and produce some output. It is conceivable that an algorithm
may have no input. An example could be one that generates a fixed report form. However, such
algorithms are rather trivial and quite rare.
✓ Several techniques have been developed expressly for the representation of algorithms.
Pseudocodes and flowcharts can be used to develop algorithms.
There are three commonly used tools to help to document program logic (the algorithm). These are
flowcharts, structured chart, and Pseudocode. We will use the three methods here. Generally,
flowcharts work well for small problems but Pseudocode is used for larger problems.

5
1.2.1 Pseudocode
Pseudocode (derived from pseudo and code) is a compact and informal high-level description of a
computer algorithm that uses the structural conventions of programming languages, but typically
omits detailes such as subroutines, variables declarations and system-specific syntax. The
programming language is augmented with natural language descriptions of the details, were
convenient, or with compact mathematical notation. The purpose of using pseudocode is that it may
be easier for humans to read than conventional programming languages, and that it may be a compact
and environment-independent generic description of the key principles of an algorithm. No standard
for pseudocode syntax exists, as a program in pseudocode is not an executable program. As the name
suggests, pseudocode generally does not actually obey the synatx rules of any particular language;
there is no systematic standard form, although any particular writer will generally borrow the
appearance of a particular language.
The programming process is a complicated one. You must first understand the program specifications,
of course, then you need to organize your thoughts and create the program. This is a difficult task
when the program is not trivial (i.e. easy). You must break the main tasks that must be accomplished
into smaller ones in order to be able to eventually write fully developed code. Writing pseudocode
will save you time later during the construction & testing phase of a program's development.
Example:
Original Program Specification:
Write a program that obtains two integer numbers from the user. It will print out the sum
of those numbers.
Pseudocode:
Prompt the user to enter the first integer
Prompt the user to enter a second integer
Compute the sum of the two user inputs
Display an output prompt that explains the answer as the sum Display the result
1.2.2. Structured Charts
Structured chart depicts the logical functions to the solution of the problem using a chart. It
provides an overview that confirms the solution to the problem without excessive consideration to
detail. It is high-level in nature.

6
Example: Write a program that asks the user to enter a temperature reading in centigrade and then
prints the equivalent Fahrenheit value.
Input Process Output
Centigrade • Prompt for centigrade value Fahrenheit
• Read centigrade value
• Compute Fahrenheit value
• Display Fahrenheit value

1.2.3 Flowchart
A flowchart (also spelled flow-chart and flow chart) is a schematic representation of an algorithm
or a process. The advantage of flowchart is it doesn’t depend on any particular programming
language, so that it can used, to translate an algorithm to more than one programming language.
Flowchart uses different symbols (geometrical shapes) to represent different processes. The
following table shows some of the common symbols.

7
Example 1: - Draw flow chart of an algorithm to add two numbers and display their result.
Algorithm description
▪ Read the rules of the two numbers (A and B)
▪ Add A and B
▪ Assign the sum of A and B to C
▪ Display the result (c)
The flow chart is:

8
Start

Read A, B

C= A+B

Print C

End

Example 2: Write an algorithm description and draw a flow chart to check a number is negative or
not.
Algorithm description.
1/ Read a number x
2/ If x is less than zero write a message negative else write a message not negative

Sometimes there are conditions in which it is necessary to execute a group of statements repeatedly.
Until some condition is satisfied. This condition is called a loop. Loop is a sequence of instructions,
which is repeated until some specific condition occurs. A loop normally consists of four parts. These
are:

9
Initialization: - Setting of variables of the computation to their initial values and setting the counter
for determining to exit from the loop.
Computation: - Processing
Test: - Every loop must have some way of exiting from it or else the program would endlessly remain
in a loop.
Increment: - Re-initialization of the loop for the next loop.
Example 3: - Write the algorithmic description and draw a flow chart to find the following sum.
Sum = 1+2+3+…. + 50
Algorithmic description
1. Initialize sum too and counter to 1
1.1. If the counter is less than or equal to 50
• Add counter to sum
• Increase counter by 1
• Repeat step 1.1
1.2. Else
• Exit
2. Write sum

10
1.1. SOFTWARE DEVELOPMENT Lifecycle

Software development method is a method of developing computer programs to solve problems


using a computer.
The software development method consists of the following steps:

1. Requirements Specification
▪ One of the most important steps in problem solving is requirements specification; that is
understanding exactly
▪ what the problem is,
▪ what is needed to solve it,
▪ what the solution should provide, and
▪ if there are constraints and conditions.
▪ How precisely we can define a problem depends on our degree of familiarity with the problem
domain. If we are not familiar with the problem domain, then we should either quickly acquire
an education in it or contact people who are knowledgeable about it. For example, by
interviewing the shop manager we can acquire knowledge and get familiarized with the
problem domain. While talking with the sales manager we can come to know different
problems that he faces.
▪ Creating a clear specification of what he requires will make the problem domain defined.
2. Analysis
In the analysis phase we should identify the following:
▪ Inputs to the problem, their form, and the input media to be used
▪ Outputs expected from the solution, their form, and the output media to be used

11
▪ Any special constraints or conditions
▪ Formulas or equations to be used
▪ Provided we have acquired a clear understanding of the problem and have a precise requirements
specification at hand, the analysis phase is usually easy. For the above sample problem, we have
the following:
o Input: Consists of Unit Price of the product, Count and the Customer’s Paying Amount.
All the inputs will be interactive, and we will use the keyboard for them.
o Output: Two types of outputs are expected. One type is as each input is entered, it will
be processed and displayed in the screen. For example, once the Unit Price and the Count
is given, it should give the Total Price. Consequently, the Grand Total. Once the
Customer’s Paying Amount is given it should display the remaining amount to be return
to the customer.
• Constraints:
o The program should not accept fractional count while giving numbers,
o When the customer pays the Amount, it should not be less than the Grand Total Amount.
If the user enters less value than the Grand Total it should prompt the error message and
ask for qualified value.
• Formulas: The formulas for calculating are:
Total Price = Unit Price * Count
Grand Total = Addition of all total price. (if the customer buys more than one product)
Remaining = Customer’s Paying Amount – Grand Total
3. Design
▪ The next step is to design a method of solution for the problem. A method of solution is a
series of steps to be performed in a specific logical order. Another name for a method of
solution is an algorithm.
▪ As with any design problem, an algorithm design should be put on paper. In other words, we
should be able to represent and document our algorithms using an appropriate way.
4. Implementation
▪ The next step in the software development method is the implementation of the algorithm in
a programming language.

12
▪ During implementation we translate each step of the algorithm into a statement in that
particular language and end up with a computer program. Therefore, we can define a computer
program as follows
▪ A computer program is a sequence of a finite number of statements expressed in a
programming language in a specific logical order that, when executed, produce the solution
for a problem.
▪ This phase consists of choosing the appropriate programming language and writing a program
following the syntax of the language exactly. Coding the program is actually writing the
program, translating the logic of the design into programming language.
5. Testing and Verification
▪ Check the correctness of the program and verify that the program will do what is expected to
do.
▪ Program Verification is the process of ensuring that a program meets user requirements. One
of the techniques that can be used for program verification is Program Testing.
▪ Program Testing is the process of executing a program to demonstrate its correctness.
▪ When you begin testing your program, you may come across some run-time errors. Naturally,
you debug them and run your program again. However, even output that seems correct is not
a guarantee that your program is completely correct. A program must be tested using a
sufficiently large sample of carefully designed test data sets such that every logical path in the
program is traversed at least once.
▪ If your program contains conditional executions of blocks of code, a single test data set may
not cause all program statements to be executed. You must continue to test your program until
you are sure that all statements in it are functioning correctly.
▪ Testing the program consists of desk-checking, debugging the program off errors, and running
real-world data to make sure the program works
▪ Desk-checking- is simply reading through, or checking the program to make sure that it is
free of errors and that the logic works
o is like proofreading
o should be taken before the program is actually run on a computer
▪ Debugging the program- means to detect, locate and remove all errors in a computer
program

13
▪ Run real-world data
▪ testing the program with real data and real users
▪ It is also advisable to test it with faulty or incomplete or overwhelming data
6. Maintenance and Documentation
▪ Maintenance includes fixing bugs, improving performance, and adding new features.
▪ Documentation involves creating and updating technical manuals, user guides, and system
records so others can understand, use, and maintain the system easily.
▪ The significance of proper documentation in the software life cycle cannot be
overemphasized.
▪ Program documentation consists of these elements:
▪ A concise requirements specification.
▪ Descriptions of problem inputs, expected outputs, constraints, and applicable
formula
▪ A pseudocode or flowchart for its algorithm.
▪ A source program listing.
▪ A hard copy of a sample test runs of the program.
▪ A user’s guide explaining to non-programmer users how the program should be
used.
1.2. LANGUAGE TRANSLATORS
✓ All computer programs run on machine code that is executed directly on computer architecture.
Machine code is not easily read or programmed directly by humans. Essentially, machine code
is a long series of bits (i.e. ones and zeroes). In order to program, humans write code in a language
that is then translated in to machine code.

✓ There are 3 types of system software used for translating the code that a programmer writes into
a form that the computer can execute (i.e. machine code). These are:
1. Assemblers
2. Compilers
3. Interpreters

14
Assemblers
▪ No matter how close assembly language is to machine code, the computer still cannot
understand it. The assembly-language program must be translated into machine code.
▪ Assembly languages are more easily translated in to machine code than high-level programs
languages. Each assembly language statement directly corresponds to one or more machine
instructions.
▪ Another way to think about this is that assembly language code is simply an abbreviated form
of machine code. Thus, to transform a program from an assembly language to machine code
all that must be done is that the instructions must be converted from their mneumonic
abbreviations into their equivalent string of ones and zeroes. This transformation process is
known as assembling and is accomplished by an assembler.

▪ The assembler program recognizes the character strings that make up the symbolic names of
the various machine operations, and substitutes the required machine code for each
instruction.
▪ The final result is a machine-language program that can run on its own at any time; the
assembler and the assembly-language program are no longer needed. To help distinguish
between the "before" and "after" versions of the program, the original assembly-language
program is also known as the source code, while the final machine-language program is
designated the object code.
▪ If an assembly-language program needs to be changed or corrected, it is necessary to make
the changes to the source code and then re-assemble it to create a new object program.
Compilers
▪ Each instruction in the compiler language can correspond to many machine instructions. Once
the program has been written, it is translated to the equivalent machine code by a program
called a compiler. Once the program has been compiled, the resulting machine code is saved
separately, and can be run on its own at any time.

15
▪ A compiler is a computer program that converts an entire program written in a high-level
language (called source code) and translates it into an executable form (called object code).
▪ Updating or correcting a compiled program requires that the original (source) program be
modified appropriately and then recompiled to form a new machine-language (object)
program.
▪ Typically, the compiled machine code is less efficient than the code produced when using
assembly language. This means that it runs a bit more slowly and uses a bit more memory
than the equivalent assembled program. To offset this drawback, however, we also have the
fact that it takes much less time to develop a compiler-language program, so it can be ready
to go sooner than the assembly-language program.
Advantages of a Compiler
▪ Fast in execution
▪ The object/executable code produced by a compiler can be distributed or executed without
having to have the compiler present.
▪ The object program can be used whenever required without the need to of re- compilation.
Disadvantages of a Compiler
▪ Debugging a program is much harder. Therefore, not so good at finding errors
▪ When an error is found, the whole program has to be re-compiled
Interpreters
▪ An interpreter is a computer program that takes source code and converts each line in
succession.

▪ At each step it executes the high-level statement. In other words, it doesn't have to examine
the entire program before it can begin executing code.
▪ Thus, programs that are interpreted lend themselves to interactive programming. However,
programs that are interpreted will generally run much slower than programs that are compiled.
▪ An Interpreter translates high-level source code into executable code. However, the
difference between a compiler and an interpreter is that an interpreter translates one line at a
time and then executes it: no object code is produced, and so the program has to be interpreted

16
each time it is to be run. If the program performs a section code 1000 times, then the section
is translated into machine code 1000 times since each line is interpreted and then executed.
Advantages of an Interpreter
▪ Good at locating errors in programs
▪ Debugging is easier since the interpreter stops when it encounters an error.
▪ If an error is deducted there is no need to retranslate the whole program. This can enormously
speed up the development and testing process.

Disadvantages of an Interpreter
▪ Because the interpreter has to scan the user's program one line at a time and execute internal
portions of itself in response, execution of an interpreted program is much slower than for a
compiled program.
▪ No object code is produced, so a translation has to be done every time the program is running.
▪ For the program to run, the Interpreter must be present. i.e. both the interpreter and the user's
program reside in memory at the same time.
1.3. C++ PROGRAM COMPILATION
▪ When a C++ program is written, it must be typed into the computer and saved to a file. A text
editor, which is similar to a word processing program, is used for this task. The statements written
by the programmer are called source code, and the file they are saved in is called the source file.
After the source code is saved to a file, the process of translating it to machine language can begin.
▪ During the first phase of this process, a program called the preprocessor reads the source code.
The preprocessor searches for special lines that begin with the # symbol. These lines contain
commands that cause the preprocessor to modify the source code in some way.
▪ During the next phase the compiler steps through the preprocessed source code, translating each
source code instruction into the appropriate machine language instruction. This process will
uncover any syntax errors that may be in the program. Syntax errors are illegal uses of key words,
operators, punctuation, and other language elements. If the program is free of syntax errors, the
compiler stores the translated machine language instructions, which are called object code, in an
object file.
▪ Although an object file contains machine language instructions, it is not a complete program.
Here is why: C++ is conveniently equipped with a library of prewritten code for performing
common operations or sometimes-difficult tasks. For example, the library contains hardware-

17
specific code for displaying messages on the screen and reading input from the keyboard. It also
provides routines for mathematical functions, such as calculating the square root of a number.
This collection of code, called the run-time library, is extensive. Programs almost always use
some part of it. When the compiler generates an object file, however, it does not include machine
code for any run-time library routines the programmer might have used.
▪ During the last phase of the translation process, another program called the linker combines the
object file with the necessary library routines. Once the linker has finished with this step, an
executable file is created. The executable file contains machine language instructions, or
executable code, and is ready to run on the computer.
The following illustrates the process of translating a source file into an executable file.

The C++ Preprocessor


▪ A C++ (or C) compiler begins by invoking the preprocessor, a program that uses special
statements, known as directives or control statements, that cause special compiler actions such
as:
▪ file inclusion, in which the file being preprocessed incorporates the contents of another
file, exactly as if the included file's text were actually part of the including file;

18
▪ macro substitution, in which one sequence of text is replaced by another;
▪ Conditional compilation, in which parts of the source file's code can be eliminated at
compile time under certain circumstances.
▪ All preprocessor directives begin with the # symbol (known as pound or hash), which must occur
in the leftmost column of the line.
1. File Inclusion
o To include a file inside the file that you are currently compiling, use the #include directive,
which takes either of two forms:
▪ #include <filename>
o Note: filename in pointy brackets which includes the given file from one of the standard
directories
▪ #include "filename"
o Note: filename in double quotes which includes the given file from the current working
directory.
o The #include directive is replaced by the entire contents of the requested file.
2. Macro Substitution
▪ A macro is a sequence of text that is defined as another (perhaps empty) sequence of text.
After a macro has been defined, whenever the preprocessor encounters that macro in the text
of the source file being preprocessed, it replaces the macro with the substitution text.
▪ To define a macro, you use the #define preprocessor directive, like so:
#define MACRO_NAME text_to_be_substituted
✓ Once MACRO NAME has been defined, then for the rest of the source file being preprocessed,
the preprocessor will replace any occurrence of MACRO NAME with text to be substituted.
✓ For example, if your source file has:
#define Integer2Byte short
#define NUMBER_OF_STUDENTS_IN_CS2413_SUMMER_2000 45
...
Integer2Byte numberOfStudents =
NUMBER_OF_STUDENTS_IN_CS2413_SUMMER_2000;
the preprocessor will delete the macro definition lines and replace the declaration statement with:
short numberOfStudents = 45;

19
✓ Note that you can define a macro with no substitution text:
#define THIS_MACRO_HAS_NO_SUBSTITUTION_TEXT
In this case, the preprocessor simply takes note of the fact that the macro exists; if it encounters
the macro within the source text, it simply deletes it. This property may seem, at first blush, to
be pretty useless, but it turns out to be very handy in conditional compilation (below).
✓ Note that you can "undefine" (eliminate) a macro definition using the #undef directive:
#undef NUMBER_OF_STUDENTS_IN_CS2413_SUMMER_2000
3. Conditional Compilation
✓ To compile conditionally, define a macro or set of macros and then use one of these:
▪ The #ifdef-#endif directive pair:
#ifdef INCREMENT_A
a = a + 1;
#endif
Note that #ifdef stands for "if has been defined;" in this case, the statement
a = a + 1;
will only be compiled if the macro named INCREMENT A has been defined. If INCREMENT A
has not been defined, then the statement will be deleted.
▪ The #ifndef-#endif directive pair:
#ifndef DECREMENT_B_AND_C
b = b - 1;
c = c - 1;
#endif
Note that #ifndef stands for "if has not been defined;" in this case, the statements
b = b - 1;
c = c - 1;
will only be compiled if DECREMENT B AND C has not been defined. If DECREMENT B AND C
has been defined, then the statements will be deleted.

20

You might also like