Question:

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

Answer:

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_FILETO_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.


Keywords:

© 2017 QuizBucket.org