Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the pointer to __FILE__ remain valid after moving out of scope?

Tags:

c++

debugging

If I want to pass __FILE__ to an object, do I need to make a copy of the string or can I just store its pointer as const char*?

I'm guessing that I need to make a copy since I think it will free itself once it moves out of scope.

Does the pointer to __FILE__ provide any guarantees?

like image 713
Zhro Avatar asked Dec 14 '22 05:12

Zhro


2 Answers

__FILE__ expands to a normal string literal. So as long as you are only reading it, you can just use a const char* like

const char *filename = __FILE__;

As string literals have static storage duration, the pointer will remain valid throughout the whole program.

If you want something modifiable, you need a copy and manage its lifetime yourself.

For a complete list of predefined standard macros and information about what they expand too, have a look at the "Predefined macros" section on this documentation page.

As @Keith Thompson correctly pointed out in a comment, different expansions of __FILE__ may or may not yield the same address, that is:

const char *f1 = __FILE__;
const char *f2 = __FILE__;
assert(f1 == f2);              // May or may not fire

I am not sure when that would bite you, but it's good to know I guess.

like image 88
Baum mit Augen Avatar answered Jan 23 '23 05:01

Baum mit Augen


__FILE__ is a preprocessor macro that is replaced by a string literal when the preprocessor runs. Any use of it is as if you typed "filename.c" into your source code. It is not a pointer, it does not have scope, and is not freed -- those are compile-time and run-time concepts which do not apply.

like image 45
John Kugelman Avatar answered Jan 23 '23 06:01

John Kugelman