What’s going on here on this C show?

Asked

Viewed 81 times

0

I’m making a program where the user enters with 10 values, and at the end of this, presents a message saying the total value.

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 couldn’t figure out 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 in case I don’t, this occurs.

What’s going on then ?

  • 2

    It is possibly a question of the compiler initializing its variables. Since you did not set the value they start, it may be that the variable started with value 1. I tested on Repl.it and resulted in 100, but Ideone resulted in 150505460. That is, if you do not initialize the variable, the behavior cannot be predicted.

  • Thanks for the answer too, and for having tested, you also showed me that I always need to initialize local variables.

1 answer

4


Whenever you create a local variable to a function, it is allocated to 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 being executed, to which point of the previous function it has to return, and so on, until it reaches the main().

One feature of this stack is that if a function is invoked, it uses part of that memory to store its local functions. After this function returns, the memory it used is released, and if later the code that called this function calls another, it uses the same memory space as the first function used to store the local variables of the second. Besides, she doesn’t care about zeroing out that memory region even after allocating space, or before releasing it again.

The result of all this is that the value you find in an uninitialized local variable will depend on which functions previously ran in that program and how they finished executing them. In other words, and by borrowing the terminology from the C standard, 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 happened to be one; it could be -1,357,928, too.

What is the lesson learned? Always initialize your local variables when declaring them. You’ll save yourself trouble sooner or later.

  • 1

    Our many thanks for the answer, I have learned much already from her, truth this, I have learned a lesson, always initialize the local variables when declaring them, I will take this lesson with me. I didn’t know it could be an indefinite value, I thought it would always be 1, and again, thank you so much for the information.

Browser other questions tagged

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