#include <stdio.h>
void print(int a = __LINE__){printf("hello %d\n", a);}
void main(){
print();
print();
print();
print();
}
The __LINE__
macro in this case expands to 3, so the print function is called 4 times with the same value. Is there a way to convince the compiler to expand this macro at the callsite, so that the print function would be called with 6,7,8,9
instead of 3,3,3,3
with features that exist in C++11?
My usecase:
In my application, I provide multiple functions that take a unique ID. The ID should be unique per callsite/location (so if the function is called two times throught the same statement, it should receive the same id). Currently, the user always has to manually type a LOCATION
macro at the callsite, like this:
#define S1(x) #x //voodoo to concat __FILE__ and __LINE__
#define S2(x) S1(x)
#define LOCATION __FILE__ S2(__LINE__)
do_stuff1(arguments, LOCATION)
do_stuff2(arguments, LOCATION)
It would be more convenient if I could save them the typing, without creating a macro for each function like this:
#define do_stuff1(do_stuff1_imp(arguments, LOCATION))
#define do_stuff2(do_stuff2_imp(arguments, LOCATION))
Hence I thought a default argument would do the trick. Is there any way to achieve this?
Justin :
You seem to be looking for std::experimental::source_location, which will be std::source_location in a future standard:\n\n#include <experimental/source_location>\n\nvoid print(std::experimental::source_location const& location\n = std::experimental::source_location())\n{\n printf(\"hello %s:%d\\n\", location.file_name(), location.line());\n}\n",
2018-11-20T18:18:19
πάντα ῥεῖ :
\n The __LINE__ macro in this case expands to 3\n\n\nSure because your function declaration is done at line 3 and the prepreprocessor expands it from there.\n\nAnother macro instead of a function declaration would do the trick well (taken from @Ejay's comment):\n\n#define print() printf(\"hello %d\\n\", __LINE__)\n\n\nSee a working example here.",
2018-11-20T18:21:30