Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I zero initialize a struct at the start of a loop using {0}, will it be zeroed out every iteration?

Tags:

c

Let's assume that I have a for loop, and a very large struct as a stack variable:

for (int x=0 ; x <10; x++)
{
    MY_STRUCT structVar = {0};
    …code using structVar…
}

Will every compiler actually zero out the struct at the start of every loop? Or do I need to use memset to zero it out?

This is a very large struct and I want to allocate it on the stack, and I need to make sure every member of it is zeroed out at the start of every iteration. So do I need to use memset?

I can manually inspect the executable that I compile, but I need to make sure if there is any standard for this, or it just depends on the compiler.

Note that this code does compile. I am using Visual Studio.

like image 470
OneAndOnly Avatar asked Sep 15 '25 13:09

OneAndOnly


2 Answers

Will every compiler actually zero out the struct at the start of every loop?

Any compiler that conforms to the C Standard will do this. From this Draft C11 Standard (bold emphasis mine):

6.8 Statements and blocks


3    A block allows a set of declarations and statements to be grouped into one syntactic unit. The initializers of objects that have automatic storage duration, and the variable length array declarators of ordinary identifiers with block scope, are evaluated and the values are stored in the objects (including storing an indeterminate value in objects without an initializer) each time the declaration is reached in the order of execution, as if it were a statement, and within each declaration in the order that declarators appear.

In the case of a for or while loop, a declaration/initializer inside the loop's scope block is reached repeatedly on each and every iteration of the loop.

like image 96
Adrian Mole Avatar answered Sep 17 '25 08:09

Adrian Mole


See 6.2.4, paragraph 6:

If an initialization is specified for the object, it is performed each time the declaration or compound literal is reached in the execution of the block; otherwise, the value becomes indeterminate each time the declaration is reached

like image 38
William Pursell Avatar answered Sep 17 '25 07:09

William Pursell