Jedi_Sk8Tricks
Jedi_Sk8Tricks

Reputation: 31

Logical Operators, Expressions & Condition Statements (boolean values)

So I am going over a few things in C programming, which I've gone over before.

However, I'm having a hard time recalling a couple of things that are becoming relevant again. I'm starting to write more complex programs, which are using more and more conditional statements, and I can't quite get them down right.

To recap, I know that in C logical operators determine a value of a condition in one of two ways, true or false. Which really equates to either 1 or 0.

Take the following expression as an example: (if x is 4, y is 5, z is 3)

x > z && y > z

Plug in the values...

4 > 3 && 5 > 3

So in terms of Boolean logic... I know that the value of this statement is actually: 1 && 1 which is 1 (true)

or... (with same variable values as declared above)

z >= x && x <= y

The value of this statement is actually: 0 && 1 which is 0 (false because of the logical &&)

So here's where I need help...

I cant remember how to equate things in a few different forms of expressions like this one: new values: x = 3, y = 0, z = -3)

x && y || z

what is the Boolean value of something like this? Without any operators like <, >, ==, and !=?

would it be...

x && y || z
1    0    1 

which is 1 for true? because the x && y becomes false (because any false with && is a false) but then its followed with the || (OR) which if there is true it is true?

Is my question making sense?

or what about an expression that looks like this... (if x = 5, y = 1)

!x + !!y

what would be the Boolean value here? Is it

!(5) + !(!)(1)
  0      1  which would be 1 true? 

Do I add the zero and one? Probably not.

I'm probably overthinking this.

Upvotes: 1

Views: 360

Answers (1)

KamilCuk
KamilCuk

Reputation: 141768

We know that (cppreference conversion):

  • zero value evaluates to false.
  • nonzero value evaluates to true. Any nonzero value. -3 is true. 1 is true. INT_MAX is true.

We also know about operator precedence:

  • && has higher precedence than ||
  • which means, first && is evaluated, then ||

We also know that true and false in C are just macros for 1 and 0 defined in stdbool.h, so they have the int type. C does not has "real" boolean values, only boolean _Bool type. The logical operators && || and ! evaluate to int(!) type values 1 or 0 only, see cppreference.

So:

3 && 0 || -3

is equal to:

(true && false) || true

which evaluates to 1.

!5 + !!1

The ! has higher precedence.

The value of ! operator is 1 (true) in case of zero. The value of ! operator is 0 (false) in case of nonzero expression.

So it's:

(! true) + (! (! true) )

false + true

0 + 1

1

Upvotes: 2

Related Questions