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?
__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.
__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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With