WhiteFlameAB - 6 months ago 48

C Question

I want to evaluate the following boolean expression in C:

`f = (b+c')(a'+c')(a+b'+c)`

This is my current program:

`#include <stdio.h>`

int main()

{

int a,b,c,f;

a=0;b=1;c=1;

f=((b|(~c))&((~a)|(~c))&(a|(~b)|c));

printf("%d\n",f);

}

The function should return 1 since a=0,b=1 and c=1 but it returns -1.

Also, when a=1,b=1 and c=1 it returns -2 instead of 0.

Why does this happen? How can I fix it?

Answer

In C you use `!`

for negation:

```
#include <stdio.h>
int main()
{
int a,b,c,f;
a=0;b=1;c=1;
f=((b||(!c))&&((!a)||(!c))&&(a||(!b)||c));
printf("%d\n",f);
}
```

The `~`

operator flips all the bits in a number, which is not what you wanted, and why you were getting -1.

Also you need `||`

instead of `|`

and `&&`

instead of `&`

. The `&`

and `|`

operators work on individual bits, where as the `||`

and `&&`

are logical operators and do what you want.