The __LINE__ Macro

Syntax

The macro is __LINE__ only, with no argument list.

Expansion

The __LINE__ macro expands differently depending on where it is used. Generally speaking, it expands to the text for an integer constant, in decimal notation, whose value is the 1-based relative line number associated with whatever line contains the macro. The line number is relative to whatever compilation unit the line came from and is subject to renumbering via the #line directive.

The Line Number Variable

Two important special cases exist, but their detailed description exceeds the present worth of these notes and a sketch must suffice for now. In both cases, __LINE__ expands not to a constant but to

(__LINE__Var+constant)

The identifier __LINE__Var names a variable and the constant is relative to whatever line number is held in the variable. The simplest demonstration has as necessary conditions that /ZI be active and that __LINE__ be used in a function. For a quick view of the overall effect, compile the fragment

int x1, x2;

void func (void)
{
    x1 = __LINE__;
    x2 = __LINE__;
}

with the /ZI option and study the assembly-language output to see __LINE__Var generated by the compiler as a long in the scope of func. To see the macro expansion, do the same but with some such fragment as

#define STRINGIZE(s)    #s
#define MACRO_TEXT(s)   STRINGIZE (s)

char *p1, *p2;

void func (void)
{
    p1 = MACRO_TEXT (__LINE__);
    p2 = MACRO_TEXT (__LINE__);
}

and notice what different strings are created for the two variables. Compile both demonstrations with /E, expecting perhaps to see the macro expansions in the preprocessor output, and wonder if it means anything that Microsoft hides what’s going on.