Behavior of __LINE__ in inline functions
Asked Answered
F

3

18

I have a macro that passes the line number and file name to an error handler:

#define SYSTEM_FAILURE (error_code, comment) \
   System_Failure((error_code), (comment), __LINE__, __FILE__);

How will the __LINE__ be resolved when used inside an inlined function?

file.h:
inline int divide(int x, int y)
{
    if (y == 0)
    {
        SYSTEM_FAILURE(ENUM_DIVIDE_BY_ZERO, "divide by zero error");
    }
    return x/y;
}

Will __LINE__ contain the line number within the header file, or the line number of the source file where the inline function is called (assuming compiler does a "paste" in the source code)?

Faraway answered 26/6, 2012 at 19:3 Comment(3)
Can't try it out as behavior may differ on compilers and may not be what the standard states.Faraway
Downvoters: Why the downvote? The question arises from using C, inline functions and macros in an embedded system.Faraway
@Thomas, testing this on your own compiler and including the results in your question (thus making it more like my preprocessor does this, is it standard?) would have (and still can) neuter many of the downvotes.Azotize
N
24

In C and C++, macros aren't (for the most part) evaluated with any knowledge of the actual code and are processed before the code (hence the name "preprocessor"). Therefore, __FILE__ would evaluate to "file.h", and __LINE__ would evaluate to the line number corresponding to the line on which SYSTEM_FAILURE appears in file.h.

Numbat answered 26/6, 2012 at 19:7 Comment(0)
S
8

Since macros are replaced by their definitions before compilation, the __LINE__ will contain the actual line of the file in which you used the macro. Inlining will not affect this behaviour at all.

Storfer answered 26/6, 2012 at 19:6 Comment(1)
He's talking about the fact that the C++ function is inline, not the macro.Zymosis
B
6

__LINE__ will be the line of the header file since the preprocessor will evaluate it before the compiler will ever see it.

Benefaction answered 26/6, 2012 at 19:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.