0

New to C/C++/C#. Is there any way to use __LINE__ to return the current line number of the input file read through stdio.h (e.g., getchar())? If not, is there another better way to do it?

2
  • 3
    No. __LINE__ is evaluated at compile-time, not run-time. Commented Sep 27, 2013 at 19:05
  • 1
    BTW, C, C++, C# are three different languages. Choose one of them, and give the standard you are interested in, e.g. C++11 Commented Sep 27, 2013 at 19:28

2 Answers 2

8

No, __LINE__ has nothing to do with the standard input. It is just macro-expanded by the compiler (to the line number inside the source code file).

If you need to count the lines of the standard input, read it line by line with getline(3) or std::getline and friends in C++ ...

Don't use fgets or the old and dead gets

Sign up to request clarification or add additional context in comments.

Comments

1

__LINE__ is a special C/C++ Preprocessor define that is translated to the source code file line number of the current line in the source code file that is being processed. It has nothing to do with any kind of input or output from the actual C/C++ program.

__LINE__ along with another special C/C++ Preprocessor define of __FILE__ is often used when generating logs to provide the source code file name (which is what __FILE__ is defined as) and the specific line number (which is what __LINE__ is defined as).

So there may be a log function, whose interface looks like log (char *pszMessage, char *pszFile, int iLineNo) and you could use it something like log ("My Log message", __FILE__, __LINE__);

These are special built-in defines whose values are changed by the Preprocessor as it opens and processes a source file.

As mentioned by Basile Starynkevitch, if you want to count lines you will need to use one of the C/C++ input functions/objects to read lines and count them as you read them.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.