Behavior of __LINE__ in inline functions

狂风中的少年 提交于 2019-12-06 17:40:45

问题


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)?


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/11214260/behavior-of-line-in-inline-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!