Can __FILE__ refer to const char * in C ++?

I had a question after reading memTrack library related to http://www.almostinfinite.com/memtrack.html

Can __FILE__ be stored in a variable of type const char* forever and no need to use strdup() ? Doesn't use BlockHeader::Stamp strdup() to assign a __FILE__ string?


 void BlockHeader::Stamp(char const *filename, int lineNum, char const *typeName) { myFilename = filename; // don't use strdup(filename) to assign? myLineNum = lineNum; myTypeName = typeName; } 

Give an example to continue to describe my question:

  //testFILE.cpp #include <iostream> const char* getStr() { return __FILE__; } void Print() { std::cout << __FILE__ << std::endl; } int main() { std::cout << getStr() << std::endl; Print(); return 0; } 

after testing, the testFILE binary can print two lines of "testFILE.cpp". That's a coincidence?

+7
c ++ macros
source share
3 answers

__FILE__ expands to a string literal during preprocessing. If you put

 const char* getStr() { return __FILE__; } 

in testFILE.cpp , then this is exactly as if you wrote

 const char* getStr() { return "testFILE.cpp"; } 

and the same rules that apply to all string literals also apply to string literals that are the result of the __FILE__ extension: the strings that they indicate exist for the entire application launch.

+9
source share

__FILE__ expands to a string literal. You can store a pointer to the (first character) string literal in a variable of type char const* . Literary lifetime coincides with the implementation of the program.

+5
source share

Thanks to everyone. I understood.

The string literal in C / C ++ is stored in the static data segment, so the literal lifetime coincides with the execution of the program.

I was confusing a string literal with a local variable.

Thanks again.

0
source share

All Articles