Programming in C: Unit I (d): Preprocessor Directives

#line

with Example C Programs | Preprocessor Directives

The #line directive enables the users to control the line numbers within the code files as well as the file name that appears when an error takes place.

#LINE

Compile the following C program:

#include <stdio.h>

main()

{

int a = 10:

printf("%d", a);

}

The above program has a compile-time error because instead of a semicolon there is a colon that ends the line, int a = 10.So when you compile this program an error is generated during the compiling process and the compiler will show an error message with references to the name of the file where the error has happened and a line number. This makes easy to detect the erroneous code and rectify it.

Programming Tip: The filename in the #line directive must be enclosed in double quotes.

The #line directive enables the users to control the line numbers within the code files as well as the file name that appears when an error takes place. The syntax of #line directive is

#line line number filename

Here, line_number is the new line number that will be assigned to the next line of code. The line numbers of successive lines will be increased one by one from this point onwards. The parameter Filename is an optional parameter that redefines the file name that will appear in case an error occurs. The filename must be enclosed within double quotes. If no filename is specified, then the compiler will show the original file name. For example:

#include <stdio.h>

main()

{

#line 10 "Error.C"

int a=10:

#line 20

printf("%d, a);

}

This code will generate an error that will be shown as error in file "Error.C", lines 10 and 20. Please execute this program with the #line directive and without the #line directive to visualize the difference.

Hence, we see that #line directive can be used to make the compiler provide more meaningful error messages.

Note

A preprocessor line control directive supplies line numbers for compiler messages. It tells the preprocessor to change the compiler's internally stored line number and filename to a given line number and filename.

Programming in C: Unit I (d): Preprocessor Directives : Tag: : with Example C Programs | Preprocessor Directives - #line