Monday, 7 November 2011

How can a program be made to print the line number where an error occurs? in C programming

How can a program be made to print the line number where an error occurs?

The ANSI C standard includes a predefined macro named _ _LINE_ _ that can be used to insert the current
source code line number in your program. This can be a very valuable macro when it comes to debugging
your program and checking for logic errors. For instance, consider the following portion of code:
int print_document(char* doc_name, int destination)
{
switch (destination)
{
case TO_FILE:
print_to_file(doc_name);
break;
case TO_SCREEN:
print_preview(doc_name);
break;
case TO_PRINTER:
print_to_printer(doc_name);
break;
default:
printf(“Logic error on line number %d!\n”, _ _LINE_ _);
exit(1);
}
}

If the function named print_document() is passed an erroneous argument for the destination parameter
(something other than TO_FILE, TO_SCREEN, and TO_PRINTER), the default case in the switch statement traps

this logic error and prints the line number in which it occurred. This capability can be a tremendous help
when you are trying to debug your program and track down what could be a very bad logic error.

Cross Reference:

V.18: What are the standard predefined macros?
V.20: How can a program be made to print the name of a source file where an error occurs?
V.21: How can you tell whether a program was compiled using C versus C++?
V.28: What are the _ _DATE_ _ and _ _TIME_ _ preprocessor commands?

No comments:

Post a Comment