C: Stop Condition Loop For

Asked

Viewed 237 times

1

Hello, could someone please explain to me what is happening in this tie stop condition for?

#include <stdio.h>

int main(void) { 

    char frase[] = "Linguagem C";
    
    for(int i = 0; frase[i]; i++) { //frase[i]?
        printf("%c", frase[i]);
    } 
    
    return 0;
}

The output is: C language
I’ve used the for several other times, but I’ve never seen a condition like this.
In the example below, it is displayed in addition to the int vector content:

#include <stdio.h>

int main(void) { 

    int vetor[] = {34, 42, -12, 984, 86, 14};
    
    for(int i = 0; vetor[i]; i++) { //A condição de parada é vetor[i]
        printf("%d\t", vetor[i]);
    }  
    
    return 0;
}

The output is: 34 42 -12 984 86 14 1 7 136112
I believe the values from 14 are probably "junk in memory". But why does it happen?

  • wants to know why the memory junk?

  • Yes; I think they are values stored in RAM because of other applications, but I would like to read your explanation please.

2 answers

0

The syntax of a for loop has the following definition:

for( inicialização ; condição_de_saída ; incremento ) {}

Your code is:

for( inicialização ; variável ; incremento ) {}

The definition of a for loop is flexible and allows until expressions are omitted, but placing a variable where a conditional expression is expected generates undefined behavior. In your case the conditional was implicitly set, but even to iterate on a char[] it is wrong pq just a user enter a string that does not end in NULL to happen a segmentation failure by the unauthorized memory access.

0

In C, there is by default the logical type/Boolean, C uses the number 0 for false and any other value other than 0 with being true. In its first case, the char vector, '0' which is the "string" terminator in C is set to 0, so when i=11, vector[11] will be equal to 0 and the for is terminated. In his second example, the code is more obscure because it can give different results, but the idea of the for will go through the data in memory until finding a 0.

  • I understood perfectly, thank you very much!

  • If the answer answered you, point it out as the answer to the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.