Harsh Patel
Harsh Patel

Reputation: 141

codeblocks gives incorrect result as output

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

Answers (4)

user8141219
user8141219

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

CIsForCookies
CIsForCookies

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

msc
msc

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

Pras
Pras

Reputation: 4044

The values for b and c are undefined in this program as they dont get initialised before they get printed

Upvotes: 0

Related Questions