Reputation: 141
My code :
#include <stdio.h>
int main(){
int a = 5;
int b,c;
if (a==4){
b = 6;
c = 7;
}
printf("%d %d\n",b,c);
}
I know result should be 0 0, but codeblocks giving answer 50 8. I tried online compiler and I got answer 0 0. So what is problem with codeblocks? I am using latest version of codeblocks and gcc c compiler. How can I avoid this kind of problems in future?
Upvotes: 0
Views: 535
Reputation:
Okay looking at your code and analyzing it step by step,
#include <stdio.h>
int main(){
int a = 5;//You've assigned the value of 5 to integer a.
int b,c;//You've declared two integer variables "b" and "c".
if (a==4)/*Compiler checks whether the if condition is true,which in your case is not*/
{
b = 6;/*Assigning value 6 to the b variable but no effect as the if condition of your's is not satisfied*/
c = 7;/*The same above condition applies here.*/
}
printf("%d %d\n",b,c);/*Here your trying to print the values of b and c,
But remember you have not given them any value. So the compiler automatically prints the garbage value(random value). It need not be 0 all the time.*/
return 0;//You forgot this step btw:)
}
Upvotes: 0
Reputation: 12807
I know result should be 0 0
Your guess is wrong
The variables b,c
are automatic (storage specifier), uninitialized variables -> indeterminate values -> no guarantee on their values -> UB!
In your case you got 50,8
you might as well get other values / print garbage/ crash...
Upvotes: 1
Reputation: 34568
The values of b
and c
variables are garbage because if()
condition become false
. It means, it is undefined behaviours.
C11 section 6.7.9 Initialization :
Paragraph 10:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
Upvotes: 1
Reputation: 4044
The values for b and c are undefined in this program as they dont get initialised before they get printed
Upvotes: 0