Quantcast
Channel: User Alex Lop. - Stack Overflow
Viewing all articles
Browse latest Browse all 39

Answer by Alex Lop. for The behavior of the for loop split between switch cases

$
0
0

default is just a label (address to where the code jumps if n is not -1 or 0).Thus when n is not -1 or 0, the flow enters the body of the for loop skipping the initialisation of j. You can write the same code also as this, so it would be clearer what is happening here:

int m = n;while (--n > 0){    switch (n)    {        case -1:        case 0:            for (int j = 0; j < m; ++j)            {        default: printf(":-)");            }            break;    }}

(Note, as mentioned by @alagner in the comments, it won't compile with C++ compiler but perfectly compiles with C one so this is good enough to make my point and explain how the code looks).

So yes, since j is uninitialised, it is undefined behaviour.If you enable compiler warnings, it will warn you about it (https://godbolt.org/z/rzGraP):

warning: 'j' may be used uninitialized in this function [-Wmaybe-uninitialized]   12 |                 for (int j = 0; j < m; ++j)      |                          ^                  

Viewing all articles
Browse latest Browse all 39

Trending Articles