Of course the answer might be compiler dependent.
However, I've compiled a programme with a loop and a block variable created in the critical section. Then I have recompiled it with the creation of the variable outside the loop.
- The assembler code generated (MSVC13, debugging mode without optimizing) is exacly the same for an unitilized variable. In fact, the compiler generates the reservation of the required stack space at entry of the function, so that nothing needs to be done when entering the critical section.
I experimented a litle bit with some variations on your question:
With intialised variable, the compiler generates the additional initialisation instructions where you put it in the code, potentially in the critical section.
With uninitialized dynamic array in the auto storage (example: char y[n];
) the principle is the same: no additional instruction will be in the critical section. Why so ? because the standard accept these dynamic arrays only if the size (here n
) is constant. So again, at code generation time, the compiler knows how much space nned to be allocated on the stack at function entry.
With more complex objects if a constructor needs to be called , then the corresponding instructions would be necessarily be performed in the critical section.
In any case, keep in mind that even when you add code in the critical section, the optimizer could still find ways to optimize it (ex: constant propagation, detecting loop invariants, etc..).
Edit
At your request, here an extract of ASM code for the first case. Sorry for the big screenshot, but it was the only mean to show code comparison easily. The difference are highlighted in yellow and gray.
You'll notice that differences are only the comments corresponding to the C++ source, and the lines where b is used (sollely, because the stack offset is named _b$1
for block variable and _b$
for function variable). (1) stack offset to access to to the variables (2) entry point in the function (3) example of local variable initialisation (4) variable in critical section (left variable is created inside the section, right outside).
