开发者

What is the type of the __LINE__ macro in C++

What is the type of the __LINE_开发者_如何转开发_ macro in C++?


C++03 §16.8p1:

__LINE__ The line number of the current source line (a decimal constant).

This will either be int, or if INT_MAX (which is allowed to be as little as 32,767) is not big enough (… I won't ask …), then it will be long int. If it would be bigger than LONG_MAX, then you have undefined behavior, which, for once, is not a problem worth worrying about in a file of at least 2,147,483,647 lines (the minimum allowed value for LONG_MAX).

The same section also lists other macros you may be interested in.


The C++ standard simply has this to say:

__LINE__: The presumed line number (within the current source file) of the current source line (an integer constant).

It does not actually state the type so it's most likely going to be the same type as an unadorned integer would be in your source code which would be an int. The fact that the upper end of the allowed range is 2G - 1 supports that (even though the lower range is 1).

The fact that #line only allows digits (no trailing U to make it unsigned) can also be read to support this.

But, that's only support. I couldn't find a definitive statement within either the C++ or C standards. It just makes sense*a that it will be translated into something like 42 when it goes through the preprocessing phase and that's what the compiler will see, treating it exactly like 42 (an int).


*a: This wouldn't be the first time my common sense was wrong, though :-)


For general C++ code, see the other answer.

In Visual Studio 2017 (and, I suspect, all other versions) __LINE__ has type long.

I used the following code to discover it:

#include <iostream>
#include <typeinfo>

template <typename T>
void print_type(T x)
{
    std::cout << x << " has type " << typeid(x).name();
}

int main()
{
    print_type(__LINE__);
}


C11, footnote 177:

The presumed source file name and line number can be changed by the #line directive.

Note: ISO/IEC Directives, Part 2:

Footnotes to the text of a document are used to give additional contextual information to a specific item in the text. The document shall be usable without the footnotes.

C11, 6.10.4 Line control:

# line digit-sequence new-line

The digit sequence shall not specify zero, nor a number greater than 2147483647.

C11, 5.2.4.2.1 Sizes of integer types <limits.h>:

Their implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown, with the same sign.

maximum value for an object of type long int

LONG_MAX +2147483647 // 2^31 − 1

Hence, I conclude that the maximum value of of __LINE__ is guaranteed to fit into long int.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜