1

How does this line work? static bool const unused = (WillOnlyRunOnce(), true)

I stumbled upon a piece of code similar to this one and I can't grasp it.

void WillOnlyRunOnce() {
    std::cout << "WillOnlyRunOnce" << std::endl;
}
void Init() {
    static bool const unused = (WillOnlyRunOnce(), true);
}
void main()
{
    Init();
    Init();
    Init();
}

2 Answers2

1

Static local variable will be initialized only at the first time control passes through the declaration and only once, so WillOnlyRunOnce() will be invoked only once too.

Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
1

unused is initialized only once when the program runs. It is initialized to whatever (WillOnlyRunOnce(), true) evaluates to.

(WillOnlyRunOnce(), true) is an expression with the comma operator. The value of the first expression is whatever WillOnlyRunOnce() returns. The value of the second expression is true. The value of the entire expression is the value of the last expression. In this case, it is true.

After unused is initialized, its value is not reset. Hence, (WillOnlyRunOnce(), true) does not get evaluated more than once. As a consequence, WillOnlyRunOnce gets called only once even when Init gets called multiple times.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thanks for your explanation. Could you please elaborate on 'After unused is initialized, its value is not reset'? What does reset mean here? Also, what will happen if it is 'reset'? –  Apr 01 '16 at 03:37
  • 1
    @abhishek_naik, you'll need a different line of code to reset its value. The initialization line is executed only once since the variable has `static` storage duration. – R Sahu Apr 01 '16 at 03:40