What's happening here in this C program?

0

I'm doing a program where the user enters 10 values, and at the end of it, displays a message saying the value total.

My code:

int rep,valor,soma;

    while(rep < 10) {

    printf("Digite um valor : ");
    scanf("%d",&valor);

    soma += valor;

    rep = rep + 1;  

    }

    printf("Total dos valores : %d ", soma);

What I could not understand is why it adds one more to the sum total, for example if the input of the 10 values is 100, it adds as 101.

Screenshot:

When I put in the code soma = 0 , it goes normal, but if I do not, this happens.

What's happening then?

    
asked by anonymous 21.06.2017 / 04:11

1 answer

4

Whenever you create a local variable for a function, it is allocated in a memory area called "the stack". It contains the local variables and some more information that allows the computer to know when a function finishes executing, at what point in the previous function it has to return, and so on, until it reaches main() .

One feature of this stack is that if a function is invoked, it uses some of that memory to hold its local functions. After that function returns, the memory it used is released, and if the code calling that function calls another function, it uses the same memory space that the first function used to store the variables locations. What's more, she does not worry about zeroing this region of memory or even allocating space before releasing it again.

The result of all this is that the value you encounter in an uninitialized local variable will depend on what functions were previously run in that program and how they ended up executing them. In other words, and borrowing C-terminology, when you read the value of an uninitialized local variable, the behavior is undefined . That is, any value can be there. In your case, it has been one; could be -1.357.928, too.

What is the lesson learned? Always initialize your local variables when declaring them . It will save you hassles sooner or later.

    
21.06.2017 / 04:22