I have a function which is passed a list of ints, until one value is “-1” and calculates the minimum.
If the function gets called couple times, it is supposed to return the minimum between all calls.
So I wrote something like that:
int min_call(int num, ...)
{
va_list argptr;
int number;
va_start(argptr, num);
//static int min = va_arg(argptr, int); //////// the questioned line
static int all_min = -1;
int min = va_arg(argptr, int);
if (min != -1)
{
while ((number = va_arg(argptr, int)) != -1)
{
if (number < min)
{
min = number;
}
}
}
if (min < all_min || all_min == -1)
{
all_min = min;
}
return all_min;
}
I want to know something about the marked line… why can’t I call it – the compiler says because the expression being used to initialize the static int is not constant.
For some reason I remember that I can initialize a static variable and know that the initializing statement will be called only once (the first time) it’s written in C++.
If that line would be available it would have saved me couple variables.
Is there a difference between C and C++ in this matter?
Yes, C++ allows for statics to be lazily initialized at runtime. Effectively C++ turn static initialization into this:
While this is convenient, it is not thread safe. The standard does not require this to be thread safe although some compilers have done that anyway (gcc 4.x does thread safe initialization unless explicitly requested not to with -fno-threadsafe-statics).
C requires statics be to have their value configured at compile time. Yes, this is more limited but is more in line with C doing little work for you behind your back (C can be thought of as portable assembly).