Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a string literal be concatenated to __FUNCTION__?

Isn't __FUNCTION__ a string literal? I'd always thought it was - along the lines of __FILE__, but I just discovered I can't adjacently concatenate a string literal to it. If it's not a string literal, what is it defined as? I can't get cscope to resolve it.

E.g.

#include <iostream>

int main( int argc, char* argv[] )
{
  std::cout << __FILE__ << std::endl;
  std::cout << __FILE__ "A" << std::endl;
  std::cout << __FUNCTION__ << std::endl;
  //std::cout << __FUNCTION__ "A" << std::endl; // Doesn't compile.
  return 0;
}

The error when the problem line is included:

>g++ --version
g++ (GCC) 4.8.3 20140911 (Red Hat 4.8.3-7)
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

>g++ -g main.cpp 
main.cpp: In function 'int main(int, char**)':
main.cpp:8:29: error: expected ';' before string constant
   std::cout << __FUNCTION__ "A" << std::endl; // Doesn't compile.
like image 961
StoneThrow Avatar asked Jan 06 '18 06:01

StoneThrow


1 Answers

Short answer, no, __FUNCTION__ is not a string literal, it's a pointer to a const char * variable containing the name of the function.

Because the __FUNCTION__ macro doesn't expand directly to the function name, instead, it expands to something like this (the exact name is probably different, but the name is stores as a pointer to char*):

 const char *func_name = "main";

 std::cout << func_name << std::endl;

And of course, if you have that code, it's quite easy to see that:

 std::cout << func_name "A" << std::endl;

will not compile.

like image 78
Mats Petersson Avatar answered Oct 03 '22 04:10

Mats Petersson