Consider the snippet below:
#include <iostream>
int f(int i) {
return ++i;
}
int i = f(i);
int main() {
std::cout << i << '\n';
}
Where in the C++ Standard can I find support for the initialization of the global variable i
above?
Initialisation of non-local variables is described in the chapter titled "Initialization of non-local variables", [basic.start.init]. In C++11, that's 3.6.2.
Initialising using =
, the initialiser can be a braced list, or any assignment expression, including a function call, as specified in [dcl.init] (C++11 8.5).
This has static storage duration, so it's first zero-initialised during static initialisation per 3.6.2/2:
Variables with static storage duration [...] shall be zero-initialized before any other initialization takes place.
It is then initialised from its initialiser during dynamic initialisation, since it doesn't meet the criteria for constant initialisation (since the initialiser isn't a constant expression). That passes the statically initialised zero value to the function, which increments it and returns 1. That value of 1 is used to complete the initialisation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.