droidlabour
droidlabour

Reputation: 697

Variable inside if block is assigned to zero even if the if expression evaluates to false in C

#include<stdio.h>
int main(void) {
    int a = 123,b,c;
    if(a>300) {
        b=200;
    }
    c=4556;
    printf("b = %d\n",b);
    return 0;
}

Now as if block evaluates to false so if block should not get executed, but the code is printing value of b as 0. Moreover if the value of c isn't assigned after the if block is over then the code shows some garbage value for b. Can anyone tell me why is this happening like this, as far as I know b must show some garbage value for the first case also.

Upvotes: 0

Views: 90

Answers (1)

mathematician1975
mathematician1975

Reputation: 21351

Unless you initialise your variables, you will not know for sure what their values are so this is not remotely surprising. If you want your b variable to contain a meaningful value, then initialise it with that value.

Upvotes: 4

Related Questions