Initialization of int affects the return value of the function

Sorry for the vagueness of this question, but I'm not sure how to ask this correctly.

The following code running on an Arduino microprocessor (C ++ compiled for an ATMega328 microprocessor) works fine. The returned values ​​are displayed in the comments in the code:

// Return the index of the first semicolon in a string
int detectSemicolon(const char* str) {

    int i = 0;

    Serial.print("i = ");
    Serial.println(i); // prints "i = 0"

    while (i <= strlen(str)) {
        if (str[i] == ';') {
            Serial.print("Found at i = ");
            Serial.println(i); // prints "Found at i = 2"
            return i;
        }
        i++;
    }

    Serial.println("Error"); // Does not execute
    return -999;
}

void main() {
    Serial.begin(250000);
    Serial.println(detectSemicolon("TE;ST")); // Prints "2"
}

This displays "2" as the position of the first semicolon, as expected.

However, if I change the first line of the function detectSemicolonto int i;, that is, without explicit initialization, I get problems. In particular, the output is "i = 0" (good), "Found at i = 2" (good), "-999" (bad!).

, -999, , return 2; , , return -999;.

- , ? , c , , , , ...


: , , , . , undefined - i. serial.prints detectSemicolon :

void setup() {
    Serial.begin(250000);
    Serial.println(detectSemicolon("TE;ST")); // Prints "2"
  d0:   4a e0           ldi r20, 0x0A   ; 10
  d2:   50 e0           ldi r21, 0x00   ; 0
  d4:   69 e1           ldi r22, 0x19   ; 25
  d6:   7c ef           ldi r23, 0xFC   ; 252
  d8:   82 e2           ldi r24, 0x22   ; 34
  da:   91 e0           ldi r25, 0x01   ; 1
  dc:   0c 94 3d 03     jmp 0x67a   ; 0x67a <_ZN5Print7printlnEii>

, while , "-999" , , 0xFC19. serial.prints, , .


2:

, , , ( UB):

https://justpaste.it/vwu8

, , -, 28 i "" d8. , i while, if .., , (, 122, "i" ).

, , ; ( 120 132, "-999" 24 25, main()).

, , . - , undefined.

+4
3

static, , int, . . , i . (, ) , .

++ 11 Standard, Angew . :

++ 11 4.1/1, lvalue-to-rvalue ( , ): " , glvalue, ... , , , undefined.

undefined, . , , , , , undefined, , .

, , - UB. , , , ( ). , , , i ..

"", , . "" UB. , .

, UB: , .

? ""?

+10

, , , , while (i <=strlen(str)) . .

( Visual Studio Debug .)

0

, , int i, , , strlen(str) , , while,

while (i <= strlen(str))

Error -999.

-1

All Articles