Reputation: 25
#include <stdio.h>
#include <stdarg.h>
int topla(int prtSayisi, ...);
int main(){
printf("%d\n", topla(5, 10, 10, 10, 10, 10));
printf("%d\n", topla(2,10,11));
printf("%d\n", topla(5,111,111,111,111,111));
printf("%d\n", topla(5, 1,2,3,5,1));
printf("%d\n", topla(2,3,2));
return 0;
}
int topla(int prtSayisi, ...){
va_list prtArg;
va_start(prtArg, prtSayisi);
int sonuc=0, i;
for (i=0;i<prtSayisi;i++){
sonuc += va_arg(prtArg, int);
}
va_end(prtArg);
return sonuc;
}
I dont have an issue whit this code but there is variable called sonuc in the function
topla(int ptrSayisi, ...);
and if i dont assign 0 to that variable the function returns something random. Why its happening?
Upvotes: 0
Views: 53
Reputation: 12698
Uninitialized automatic variables contain garbage. The reason is that they are placed in the program stack, where the contents of previous stack data remains on function entry (only the stack pointer is updated on popping data, and not the stack data itself), if you don't initialize them.
Initializing local variables requires specific code to be executed to do the task, to be compiled in the code of the function, and this affects efficiency of code (each time the function is called, the stack space used by it should be cleaned), so the designers of C language preferred to initialize the space only when the programmer stated so, explicitly. This feature is explained in almost all C books around (also in the C standard) and is so since the first C compiler existent.
Today, almost every compiler warns you when you leave a variable and use it without a proper initialization. Always that the variable is used in an expression without an explicit previous initialization (as the first pass of the loop, you write sonuc += va_arg(prtArg, int);
--which is equivalent to sonuc =
sonuc
+ va_arg(ptrArg, int);
) the compiler warns you about sonuc
being used in an expression without being first initialized.
Upvotes: 1
Reputation: 224377
The +=
operator adds the value of the right side to the current value of the object on the left side. If you don't initialize sonuc
its value is indeterminate, which roughly means that there is no guarantee that it will hold any particular value or even that you will read the same value on a subsequent read.
This means you're attempting to add something to an indeterminate value. Reading a variable whose value is indeterminate can trigger undefined behavior.
By initializing the variable, it starts at a known value.
Upvotes: 1