0% found this document useful (0 votes)
12 views

TTS_Module15-CC102

COMPUTER PROGRAMMING

Uploaded by

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

TTS_Module15-CC102

COMPUTER PROGRAMMING

Uploaded by

darwinteberio0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

SELF-PACED LEARNING

MODULE
College

.
INFORMATION SHEET FN-5.1.1
“Preprocessors and Error Handling”
Preprocessors
The C Preprocessor is not part of the compiler, but is a separate step in the compilation process.
In simplistic terms, a C Preprocessor is just a text substitution tool and they instruct compiler to do
required pre-processing before actual compilation. We'll refer to the C Preprocessor as the CPP.
All preprocessor commands begin with a pound symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in first column. Following section
lists down all important preprocessor directives:

Preprocessors Examples
Analyze following examples to understand various directives.

This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for
constants to increase readability

These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source
file. The next line tells CPP to get myheader.h from the local directory and add the content to the
current source file.
This tells the CPP to undefine existing FILE_SIZE and define it as 42

This tells the CPP to define MESSAGE only if MESSAGE isn't already defined.

This tells the CPP to do the process the statements enclosed if DEBUG is defined. This is useful if you
pass the -DDEBUG flag to gcc compiler at the time of compilation. This will define DEBUG, so you can
turn debugging on and off on the fly during compilation.

Predefined Macros
ANSI C defines a number of macros. Although each one is available for your use in programming, the
predefined macros should not be directly modified

Let's try the following example:


#include <stdio.h>
main()
{
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("ANSI :%d\n", __STDC__ );
}
When the above code in a file test.c is compiled and executed, it produces the following result:
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1
Preprocessor Operators
The C preprocessor offers following operators to help you in creating macros:
Macro Continuation (\)
A macro usually must be contained on a single line. The macro continuation operator is used to
continue a macro that is too long for a single line. For example:

Stringize (#)
The stringize or number-sign operator ('#'), when used within a macro definition, converts a macro
parameter into a string constant. This operator may be used only in a macro that has a specified
argument or parameter list. For example:

When the above code is compiled and executed, it produces the following result:

Token Pasting (##)


The token-pasting operator (##) within a macro definition combines two arguments. It permits two
separate tokens in the macro definition to be joined into a single token. For example:

When the above code is compiled and executed, it produces the following result:
token34 = 40
How it happened, because this example results in the following actual output from the preprocessor:
printf ("token34 = %d", token34);
This example shows the concatenation of token##n into token34 and here we have used both stringize
and token-pasting.

The defined() Operator


The preprocessor defined operator is used in constant expressions to determine if an identifier is
defined using #define. If the specified identifier is defined, the value is true (non-zero). If the symbol is
not defined, the value is false (zero). The defined operator is specified as follows:

When the above code is compiled and executed, it produces the following result:
Here is the message: You wish!

Parameterized Macros
One of the powerful functions of the CPP is the ability to simulate functions using parameterized
macros. For example, we might have some code to square a number as follows:
int square(int x) {
return x * x;
}
We can rewrite above code using a macro as follows:
#define square(x) ((x) * (x))

Macros with arguments must be defined using the #define directive before they can be used. The
argument list is enclosed in parentheses and must immediately follow the macro name. Spaces are not
allowed between and macro name and open parenthesis. For example:
When the above code is compiled and executed, it produces the following result:
Max between 20 and 10 is 20

Error Handling
As such C programming does not provide direct support for error handling but being a system
programming language, it provides you access at lower level in the form of return values. Most of the C
or even Unix function calls return -1 or NULL in case of any error and sets an error code errno is set
which is global variable and indicates an error occurred during any function call. You can find various
error codes defined in <error.h> header file.
So a C programmer can check the returned values and can take appropriate action depending on
the return value. As a good practice, developer should set errno to 0 at the time of initialization of the
program. A value of 0 indicates that there is no error in the program.

The errno, perror() and strerror()


The C programming language provides perror() and strerror() functions which can be used to display the
text message associated with errno.
 The perror() function displays the string you pass to it, followed by a colon, a space, and then
the textual representation of the current errno value.
 The strerror() function, which returns a pointer to the textual representation of the current
errno value.
Let's try to simulate an error condition and try to open a file which does not exist. Here I'm using both
the functions to show the usage, but you can use one or more ways of printing your errors. Second
important point to note is that you should use stderr file stream to output all the errors.
#include <stdio.h>
#include <errno.h>
#include <string.h>
extern int errno ;
int main ()
{
FILE * pf;
int errnum;
pf = fopen ("unexist.txt", "rb");
if (pf == NULL)
{
errnum = errno;
fprintf(stderr, "Value of errno: %d\n", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
}
else {
fclose (pf); }
return 0;
}

When the above code is compiled and executed, it produces the following result:
Divide by zero errors
It is a common problem that at the time of dividing any number, programmers do not check if a divisor is
zero and finally it creates a runtime error.

The code below fixes this by checking if the divisor is zero before dividing:

When the above code is compiled and executed, it produces the following result:
Division by zero! Exiting...
Program Exit Status
It is a common practice to exit with a value of EXIT_SUCCESS in case of programming is coming
out after a successful operation. Here, EXIT_SUCCESS is a macro and it is defined as 0.
If you have an error condition in your program and you are coming out then you should exit with
a status EXIT_FAILURE which is defined as -1. So let's write above program as follows:

When the above code is compiled and executed, it produces the following result:
Value of quotient : 4

Reference: Workbook in C Programming Computer Programming 1 by Paulino H. Gatpandan, Azenith M. Rollan


https://www.unf.edu/~wkloster/2220/ppts/cprogramming..pdf
SELF CHECK FN-5.1.1

A. What is the output of the following code?


SELF CHECK ANSWER KEY FN-5.1.1

A.
STUDENT NAME: __________________________________ SECTION: __________________

PERFORMANCE TASK FN-5.1.1


PERFORMANCE TASK TITLE: C Program

PERFORMANCE OBJECTIVE: The learners independently demonstrate core competencies about C


programs
MATERIALS:
Computer / Android phone
Applications / Software:
Computer: TurboC2
Android phone: Coding C
Procedure:
A. Create your own program based on all lessons. (Any topic).
(screenshot the output and code)

PRECAUTIONS:
 Undertake final inspections to ensure the program conform to requirements
ASSESSMENT METHOD: PERFORMANCE TASK CRITERIA CHECKLIST
STUDENT NAME: __________________________________ SECTION: __________________

PERFORMANCE TASK CRITERIA CHECK LIST FN-5.1-1


SCORING
CRITERIA
1 2 3 4 5
1. Quality of Work – the ability to follow procedures with precision and the
art, skill and finality of work
2. Speed – efficiency of work
3. Proper use of statement – the ability to apply proper statement for a
given task
TEACHER’S REMARKS:  QUIZ  RECITATION  PROJECT
GRADE:

5 - Excellently Performed
4 - Very Satisfactorily Performed
3 - Satisfactorily Performed
2 - Fairly Performed
1 - Poorly Performed

_________________________________
TEACHER

Date: ______________________

You might also like