C++: Declare static variable in function argument list

Posted by MDC on Stack Overflow See other posts from Stack Overflow or by MDC
Published on 2011-01-04T15:32:10Z Indexed on 2011/01/04 15:54 UTC
Read the original article Hit count: 159

Filed under:

Is there any way at all in C++ to declare a static variable while passing it to a function? I'm looking to use a macro to expand to the expression passed to the function. The expression needs to declare and initialize a static variable on that particular line (based on the filename and line number using FILE and LINE).

int foo(int b)
{
     int c = b + 2;
     return c;
}

int main()
{
     int a = 3;
     a = foo(static int h = 2); //<---- see this!
     cout << a;
     return 0;
}

The problem I'm trying to solve is getting the filename and line number with the FILE and LINE macros provided by the preprocessor, but then creating a lookup table with integer keys leading to the FILE, LINE pairs. For example, the key 89 may map to file foo.cpp, line 20. To get this to work, I'm trying to use local static variables, so that they are initialized only once per line execution. The static variable will be initialized by calling a function that calculates the integer key and adds an entry to the lookup table if it is not there.

Right now the program uses a message class to send exception information. I'm writing a macro to wrap this class into a new class: WRAPPER_MACRO(old_class_object) will expand to NewClass(old_class_object, key_value). If I add the static variable declaration as a second line right before this, it should work. The problem is that in most places in the code, the old class object is passed as an argument to a function. So the problem becomes declaring and initializing the static variable somehow with the macro, while keeping the existing function calls.

© Stack Overflow or respective owner

Related posts about c++