Can anyone explain why this code prints garbage values?
int main(){
int a, b, sum;
sum = a b;
scanf("%d%d",&a,&b);
printf("addition is %d", sum);
return 0;
}
But if I write code like this it prints the correct value?
int main(){
int a, b, sum;
scanf("%d%d",&a,&b);
sum = a b;
printf("addition is %d", sum);
return 0;
}
CodePudding user response:
That's because C is an imperative language and each line is like a command, executed from top to bottom. So in this case:
int main(){
int a, b, sum; // create 3 variables: a, b and sum. Garbage on start
sum = a b; // add 'a' and 'b' and save it in 'sum'. Still garbage
scanf("%d%d",&a,&b); // read 2 numbers and save them in 'a' and 'b'. Nowe they're valid, but 'sum' is still garbage
printf("addition is %d", sum); // print 'sum'. That's garbage
return 0;
}
By simply reordering the operations (adding a
and b
after reading their values) we get valid result
CodePudding user response:
sum = a b;
is not a definition or a formula, it's a statement - it's executed as soon as it is encountered, with whatever values are in a
and b
(which are indeterminate).
C just isn't that high-level.