user11954200
user11954200

Reputation:

Boolean tests with integers in C

The following works in C without giving a warning:

int holding_variable = (-5 && 1);
int holding_variable = (1 && 1);
int holding_variable = (0 && 0);

Yet the following gives warning (numbers are greater than 1):

int holding_variable = (-5 && 2);
int holding_variable = (2 && 2);

An example warning would be:

$ gcc main.c -o main.out && ./main.out
main.c:66:28: warning: use of logical '&&' with constant operand [-Wconstant-logical-operand]
    int holding_variable = (1 && -1);
                              ^  ~~
main.c:66:28: note: use '&' for a bitwise operation
    int holding_variable = (1 && -1);
                              ^~
                              &
main.c:66:28: note: remove constant to silence this warning
    int holding_variable = (1 && -1);
                             ~^~~~~
1 warning generated.

What accounts for the difference in the above two categories as to why the first will execute but the second ones will not?

Upvotes: 0

Views: 238

Answers (1)

J CHEN
J CHEN

Reputation: 494

For Not 0 value is true, like below

int main(){ 

    int i;
    for(i=-3;i<=3;i++){
        if(i){
            printf("True :%d\n",i);
        }else{
            printf("False :%d\n",i);
        }
    }

    return 0;
}

So if you don't want warn using & is right in your case

because 0 & X is always 0

and add a function if you only want 0 or 1

int BeBool(int a){
    if(a){
        return 1;
    }
    return 0;
}

int holding_variable = BeBool(2&2);

instead int holding_variable = (2 && 2);


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int BeBool(int a){
    if(a){
        return 1;
    }
    return 0;
}

int main(){ 

    int i;
    for(i=-3;i<=3;i++){
        if(i){
            printf("True :%d\n",i);
        }else{
            printf("False :%d\n",i);
        }
    }
    int holding_variable = BeBool(2&2);
    printf("Value :%d\n",holding_variable);
    return 0;
}

Upvotes: 1

Related Questions