-1

I was looking through 'while loop' and figured that the result was different when I declared variables = 0 and when I did not in the loop.

I am not sure why it makes different result...

Here`s example!

#include<stdio.h>
int main(){

    int even=0;
    int total=0;

    do{
        total+=even;
        even+=2;
    }while(even<=100);

    printf("total : %d", total);

    return 0;

} 

result total : 2550

#include<stdio.h>    
int main(){

    int even;
    int total;

    do{
        total+=even;
        even+=2;
    }while(even<=100);

    printf("total : %d", total);

    return 0;

} 

result total:2551

San Kim
  • 1
  • 1

1 Answers1

0

The following is undefined behaviour:

int even;
int total;
total += even;

Before reading from a variable with automatic storage duration, you must initialize it or assign to it.

ikegami
  • 367,544
  • 15
  • 269
  • 518