What is C Logical AND Operator Explained- Embedded C Programming Course Online

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

Free C Programming Course • Chapter 4 • Lecture 7

C Logical AND Operator Explained

Understand logical expressions in C: true and false rules, the AND operator with truth tables, short-circuit evaluation, NULL guards and the && versus & trap. Free C tutorial for embedded C programming.

3
Logical operators in C
2
Possible results: 0 or 1
7
Runnable programs

Welcome back to our free C programming course. You can now compare two values. This lecture teaches you how to combine comparisons into real conditions with the logical operators, starting with AND.

In this free C tutorial we also uncover short-circuit evaluation, a feature that protects your programs from crashes and is a favourite topic in embedded C programming interviews. Every example is compiled and its output is shown exactly as the compiler produced it.

What You Will Learn

  • What a logical expression is and how C defines true and false
  • The three logical operators: AND, OR and NOT
  • The AND (&&) truth table and worked examples
  • Short-circuit evaluation and why it matters
  • Using AND for NULL guards and range checks
  • The difference between && and &
  • Common mistakes and best practices

Key Terms in This Lecture

logical expression AND operator truth table non-zero is true short-circuit NULL guard range check bitwise vs logical embedded C programming free embedded C course

Prerequisites

Before you start

  • Relational operators from the previous lecture.
  • Basic if statements (a preview is enough).
  • Variables and printf.

Why Logical Operators Matter in a Free C Programming Course

A single comparison is rarely enough. Real programs ask compound questions: is the battery above 20 percent and the charger unplugged, is the key pressed or the timer expired, is the buffer not empty. C combines simple questions into bigger ones with the logical operators. Learning them is a key milestone in any free C programming course, and in embedded C programming you will use them in nearly every interrupt handler, state machine and driver.

An expression that joins two or more expressions with a logical operator is called a logical expression. The operands can be constants, variables or whole expressions, including relational ones from the last lecture. The result is always the integer 0 for false or 1 for true.

The Three Logical Operators in C

OperatorNameKindResult is 1 when
&&ANDBinary (two operands)Both operands are true
||ORBinary (two operands)At least one operand is true
!NOTUnary (one operand)The operand is false

Logical NOT takes one operand and flips it, while AND and OR take two. In this lecture we study AND in depth. OR and NOT follow in the next lecture of this free C tutorial.

What Counts as True and False in C

Before using these operators you must understand how C decides whether a value is true. There is no special true value in the language itself: any non-zero value is true and zero is false. That rule covers integers, characters, floating-point values and pointers.

The truth rule in C

Value is 0→False
Value is anything else (5, -7, 0.5, a non-NULL pointer)→True

Be careful with the word “true”

A value like 5 or -7 counts as true when tested, but the result of a logical operator is always exactly 1 or 0. So 2 && 3 gives 1, not 3.

The AND Operator in This Free C Programming Course

The AND operator gives a true result only if both conditions are true. If either side is false, the result is false. This is the rule written as a truth table, which is how engineers check digital logic:

Condition 1Condition 2Condition 1 && Condition 2
False (0)False (0)False (0)
False (0)True (non-zero)False (0)
True (non-zero)False (0)False (0)
True (non-zero)True (non-zero)True (1)

We can make the compiler print the same table for us:

#include <stdio.h>

int main(void)
{
    int p, q;

    printf(" p  q | p && q\n");
    printf("------+-------\n");
    for (p = 0; p <= 1; p++)
        for (q = 0; q <= 1; q++)
            printf(" %d  %d |   %d\n", p, q, p && q);
    return 0;
}
gcc -std=c11 -Wall -Wextra -o ep_truth ep_truth.c
./ep_truth
 p  q | p && q
------+-------
 0  0 |   0
 0  1 |   0
 1  0 |   0
 1  1 |   1

AND works like two switches in series

Switch A closed?→Switch B closed?→Lamp ON only if both are closed

Example 1: Evaluating Real AND Expressions

Take three variables a = 10, b = 5, c = 0. The expression (a == 10) && (b < a) has two parts. The first part is true because a is 10. The second part is true because 5 is less than 10. Both are true, so the whole expression is true and its value is 1.

#include <stdio.h>

int main(void)
{
    int a = 10, b = 5, c = 0;

    printf("a = %d, b = %d, c = %d\n", a, b, c);
    printf("(a == 10) && (b < a) -> %d\n", (a == 10) && (b < a));
    printf("(a == 10) && (b > a) -> %d\n", (a == 10) && (b > a));
    printf("(b >= a) && (b == 3) -> %d\n", (b >= a) && (b == 3));
    printf("a && b               -> %d\n", a && b);
    printf("a && c               -> %d\n", a && c);
    printf("-7 && 0.5            -> %d\n", -7 && 0.5);
    return 0;
}
gcc -std=c11 -Wall -Wextra -o ep_and_table ep_and_table.c
./ep_and_table

Expected output:

a = 10, b = 5, c = 0
(a == 10) && (b < a) -> 1
(a == 10) && (b > a) -> 0
(b >= a) && (b == 3) -> 0
a && b               -> 1
a && c               -> 0
-7 && 0.5            -> 1
ExpressionReads asResultValue
(a == 10) && (b < a)true && truetrue1
(a == 10) && (b > a)true && falsefalse0
(b >= a) && (b == 3)false && falsefalse0
a && b10 and 5 are both non-zerotrue1
a && ctrue && false (c is 0)false0

The last line of the program, -7 && 0.5, shows that negative numbers and fractions are true too. Only an exact zero is false.

Short-Circuit Evaluation: Free C Programming Course Insight

Here is a feature that makes && far more than a simple truth-table operator. C evaluates the left operand first. If the left operand is false, the result must be false no matter what the right operand is, so C skips the right side completely. This is called short-circuit evaluation, and the standard guarantees it.

#include <stdio.h>

static int ep_probe(const char *name, int value)
{
    printf("  evaluating %s\n", name);
    return value;
}

int main(void)
{
    int r;

    printf("Case 1: left is false\n");
    r = ep_probe("left", 0) && ep_probe("right", 1);
    printf("  result = %d\n", r);

    printf("Case 2: left is true\n");
    r = ep_probe("left", 1) && ep_probe("right", 1);
    printf("  result = %d\n", r);
    return 0;
}
gcc -std=c11 -Wall -Wextra -o ep_short ep_short.c
./ep_short
Case 1: left is false
  evaluating left
  result = 0
Case 2: left is true
  evaluating left
  evaluating right
  result = 1

Short-circuit flow of left && right

Evaluate left→Left false?→Stop: result 0, right never runs
Evaluate left→Left true?→Evaluate right, result = right

In case 1 the word “right” never appears: the function on the right was never called. In case 2 both were called. This behaviour is not a curiosity. You will use it every day.

Use Case: Guard Against a NULL Pointer

Reading through a NULL pointer crashes the program (or on a microcontroller, triggers a fault). Short-circuit AND lets you test the pointer and use it in one expression:

#include <stdio.h>
#include <stddef.h>

struct ep_packet {
    int len;
};

static int ep_ok(const struct ep_packet *p)
{
    return p != NULL && p->len > 0;     /* safe: p->len not read if p is NULL */
}

int main(void)
{
    struct ep_packet good = { 12 };
    struct ep_packet empty = { 0 };

    printf("good  : %d\n", ep_ok(&good));
    printf("empty : %d\n", ep_ok(&empty));
    printf("NULL  : %d\n", ep_ok(NULL));
    return 0;
}
good  : 1
empty : 0
NULL  : 0

When p is NULL the left side is false, so p->len is never read. Without short-circuiting the code would crash.

Use Case: Range Validation

Remember the lesson from the last lecture: 10 < x < 50 is not a range test. Two relational expressions joined by AND are:

#include <stdio.h>

static int ep_in_range(int v, int lo, int hi)
{
    return (v >= lo) && (v <= hi);
}

int main(void)
{
    int readings[] = { -50, 0, 25, 85, 125, 200 };
    int i;

    for (i = 0; i < 6; i++)
        printf("temp %4d C -> %s\n", readings[i],
               ep_in_range(readings[i], -40, 125) ? "valid" : "out of range");
    return 0;
}
temp  -50 C -> out of range
temp    0 C -> valid
temp   25 C -> valid
temp   85 C -> valid
temp  125 C -> valid
temp  200 C -> out of range

This pattern is everywhere in embedded C programming: valid sensor window, legal register value, packet length between a minimum and a maximum.

Side Effects on the Right Side May Not Happen

#include <stdio.h>

int main(void)
{
    int x = 0, y = 5;

    if (x != 0 && y++ > 3)
        printf("inside if\n");
    printf("x = %d, y = %d\n", x, y);

    x = 1;
    if (x != 0 && y++ > 3)
        printf("inside if\n");
    printf("x = %d, y = %d\n", x, y);
    return 0;
}
x = 0, y = 5
inside if
x = 1, y = 6

When x is 0 the right side never runs, so y is not incremented. Once x becomes 1 the right side runs and y becomes 6. If you hide an important change inside the right operand, it will only happen some of the time. Keep side effects out of conditions, or make the dependence obvious.

Embedded warning: skipped hardware reads

On many microcontrollers, reading a status register clears flags or pops a FIFO. If such a read sits on the right of &&, it will be skipped whenever the left side is false. Read the register into a variable first if you need the read to always happen.

Logical AND vs Bitwise AND

The two operators look similar but do different jobs. && treats each operand as true or false and gives 0 or 1. & works on individual bits and gives a number.

#include <stdio.h>

int main(void)
{
    int a = 6, b = 3;           /* 110 and 011 */

    printf("a &  b = %d\n", a & b);
    printf("a && b = %d\n", a && b);

    int flags = 0x04;
    int mask  = 0x01;
    printf("flags & mask  = %d\n", flags & mask);
    printf("flags && mask = %d\n", flags && mask);
    return 0;
}
a &  b = 2
a && b = 1
flags & mask  = 0
flags && mask = 1
Feature&& logical AND& bitwise AND
Operates onWhole values as true/falseEach bit separately
Result0 or 1Any integer
Short-circuitYesNo, both sides always evaluated
Typical useConditions in if and whileMasks and register bits

With 6 (binary 110) and 3 (binary 011), 6 & 3 is 2, but 6 && 3 is 1. Using the wrong one is a favourite interview trap.

Precedence: Do You Need Parentheses?

Relational operators bind tighter than &&, so a == 10 && b < a already means (a == 10) && (b < a). Arithmetic binds tighter than both. Still, adding parentheses is recommended because it removes any doubt and helps the next reader. && also has higher precedence than ||, which matters when you mix them. We cover that in the next lecture.

Common Mistakes and Troubleshooting

MistakeProblemFix
if (x > 10 & y < 5)Bitwise & instead of &&; works by luck and skips short-circuitUse &&
if (a == 1 && b = 2)Assignment instead of comparison on the rightUse ==
if (0 < x < 10)Chained comparison is not a range check0 < x && x < 10
Expecting 2 && 3 to be 3Result is always 0 or 1Use the value 1
Side effect on right of &&Right side sometimes skippedDo the action in its own statement
Dereferencing before the NULL checkCrash or faultPut the NULL test first on the left

Best Practices, Performance and Security

  • Put the cheap or protective test on the left: NULL checks, bounds checks, flag tests.
  • Order conditions so the most likely false one comes first; the compiler can then skip the expensive right side.
  • Use parentheses around each comparison for readability.
  • Never place essential side effects on the right operand of &&.
  • Security: many buffer-overflow bugs come from forgetting a bounds check. Write i < size && buf[i] != 0 so the index is checked before the read.
  • For safety-critical code, follow coding standards such as MISRA C that restrict side effects in logical operands.

Real-world uses you will meet

  • if (uart_ready && !error) before sending a byte.
  • while (retries > 0 && !ack) in a communication loop.
  • Checking that a pointer is valid and a length is positive before copying data.
  • Making sure the temperature is inside the valid sensor window.

Summary and Key Takeaways

  • C has three logical operators: &&, || and !; AND and OR are binary, NOT is unary.
  • Any non-zero value is true; zero is false; logical operators return exactly 1 or 0.
  • && is true only when both operands are true.
  • && short-circuits: if the left side is false the right side is not evaluated.
  • Use && for conditions and & for bit masks; never mix them up.
  • Put guards such as NULL and bounds checks on the left of the AND.

Conclusion

The AND operator is the first tool that lets you describe real conditions in C. You learned the truth table, the non-zero rule, short-circuit evaluation and how it protects your program from crashes. These ideas carry directly into the next lecture, where OR and NOT complete the set and we study how they combine in longer conditions. Keep practising: write each expression on paper, predict the value, then compile and verify. That discipline is exactly what you need for embedded C programming interviews.

Practice Quiz: Logical AND

Q1. What is 2 && 3?

Show answer

1. Both operands are non-zero, and the result of a logical operator is 1, not 3.

Q2. What is 5 && 0 && 3?

Show answer

0. The expression is evaluated left to right and the zero makes it false.

Q3. What is -1 && 1?

Show answer

1. Negative numbers are true.

Q4. What is 'A' && 0.0?

Show answer

0. The character is true, but 0.0 is false.

Q5. int x = 0, y = 5; if (x != 0 && y++ > 3) {} What is y afterwards?

Show answer

5. The left side is false, so y++ is never evaluated.

Q6. What is the difference between 6 & 3 and 6 && 3?

Show answer

6 & 3 is 2 (bitwise AND of 110 and 011). 6 && 3 is 1 (both true).

Q7. Why is p != NULL && p->len > 0 safe?

Show answer

Because of short-circuiting: if p is NULL the right side is never evaluated.

Q8. Does if (10 < x && x < 50) correctly check a range?

Show answer

Yes. Each comparison is evaluated separately and both must be true.

Interview Questions on the AND Operator

Q1. What does short-circuit evaluation mean?

Show answer

For && the right operand is evaluated only if the left operand is true. For || the right operand is evaluated only if the left is false.

Q2. What does && return?

Show answer

Always the integer 1 or 0.

Q3. How does C decide true and false?

Show answer

Zero is false and any non-zero value is true.

Q4. Difference between && and &?

Show answer

&& is logical, works on truth values, short-circuits and gives 0 or 1. & is bitwise, works bit by bit and always evaluates both sides.

Q5. Why put a NULL check on the left?

Show answer

Because evaluation stops at a false left operand, preventing the dereference on the right.

Q6. Is it safe to put a function call with side effects on the right of &&?

Show answer

Only if you are happy for it to be skipped. Otherwise call it in a separate statement.

Frequently Asked Questions About Logical AND in C

What does && mean in C?

It is the logical AND operator. It gives 1 only if both operands are true (non-zero) and 0 otherwise.

What is short-circuit evaluation in C?

When the left side of && is false, C skips the right side because the result is already known to be false.

Can && be used with pointers?

Yes. A non-NULL pointer is true and NULL is false, so p && p->next is a common idiom.

What is the difference between & and && in C?

& is bitwise AND and works on bits; && is logical AND and works on truth values.

Does 2 && 3 return 3 in C?

No. It returns 1. Logical operators always return 0 or 1.

Is there a free C programming course for embedded systems?

Yes. EmbeddedPathashala provides a free C programming course with runnable examples, quizzes and interview questions for embedded C programming.

Where can I get a free embedded C course with practice questions?

This free embedded C course includes practice quizzes and interview questions at the end of every lecture.

Next: Logical OR and NOT in C

Continue the free C programming course with the OR and NOT operators, then learn how to mix AND, OR and NOT in longer conditions with the correct precedence.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *