Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining calling line without macro

Is it possible to determine the line number that calls a function without the aid of a macro?

Consider this code:

#include <iostream>

#define PrintLineWithMacro() \
  std::cout << "Line: " << __LINE__ << std::endl;   // Line 4

void PrintLine()
{
  std::cout << "Line: " << __LINE__ << std::endl;   // Line 8
}

int main(int argc, char **argv)
{
  PrintLine();           // Line 13
  PrintLineWithMacro();  // Line 14
  return 0;
}

which outputs the following:

Line: 8
Line: 14

I understand why each prints what they do. I am more interested if it's possible to mimic the macro function without using a macro.

like image 770
elmt Avatar asked Aug 11 '26 05:08

elmt


1 Answers

I would do the following:

#define PrintLine() PrintLine_(__LINE__)

void PrintLine_(int line) {
    std::cout << "Line: " << line << std::endl;
}

I know that this doesn't completely remove the preprocessor, but it does move most of the logic into an actual function.

like image 62
Bill Lynch Avatar answered Aug 13 '26 19:08

Bill Lynch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!