Is the For-Loop Counter Remaining?

Simple question. Imagine this in ANSI-C:

int i;

for(i=0 ; i<5 ; i++){
   //Something...
}

printf("i is %d\n", i);

Will this pin "i be 5"?

Is it istored or is it iundefined after the loop?

+5
source share
5 answers

Yes. If I am declared outside the for loop, it stays in the scope after the loop finishes. It saves any value that existed at the exit point of the loop.

If you declared I in a loop:

for (int i = 0 ; i < 5 ; i++)
{

}

Then I am undefined after the exit loop.

+14
source

The variable i is defined outside the loop area (which is great, or you won’t be able to print it in this case).

, ", 5".

, , 5.

, C. "" , .

+1

i 5 . -

i = 50000;

.

+1

"i" , - . , :

for(i = 0; i < num_elements; i++)
{
    if(element[i].id == id)
    {
        /* Do something to element here. */
        break;
    }
}

if(i == num_elements)
{
    fprintf(stderr, "Failed to find element %d.", id);
    succeeded == false;
}

, . , . .

succeeded = false;

for(i = 0; i < num_elements; i++)
{
    if(element[i].id == id)
    {
        /* Do something to element here. */
        succeeded = true;
        break;
    }
}

if(false == succeeded)
{
    fprintf(stderr, "Failed to find element %d.", id);
}
0

, , . :

#include <stdio.h>

void main(int argc, char *argv[])
{
    if(argc == 2) {
        int x;
        x = 7;
    }

    x = 1;
}

:

gcc ex.c
ex.c: In function ‘main’:
ex.c:10: error: ‘x’ undeclared (first use in this function)
ex.c:10: error: (Each undeclared identifier is reported only once
ex.c:10: error: for each function it appears in.)
0

All Articles