← Back to C Course | Chapter 3: Operators | Lesson 4 of 9

C Logical Operators

Logical AND (&&)

&& (logical AND) evaluates to true only when both the left and right conditions are true -- useful whenever an action should only happen if multiple requirements are satisfied at once, like checking a value is both positive and below a limit.

Example: Logical AND (&&)

c
#include <stdio.h>
int main() {
	int age = 25;
	int hasID = 1;
	if (age >= 18 && hasID) {
		printf("Allowed");
	}
	return 0;
}

Logical OR (||)

|| (logical OR) evaluates to true if at least one of its two conditions is true -- useful for accepting any of several valid cases, like checking whether input matches one option or another.

Example: Logical OR (||)

c
#include <stdio.h>
int main() {
	char grade = 'B';
	if (grade == 'A' || grade == 'B') {
		printf("Good grade");
	}
	return 0;
}

Logical NOT (!)

! (logical NOT) flips a condition's truth value: applied to something true it becomes false, and applied to something false it becomes true -- handy for writing a condition as "not X" instead of restructuring the whole check.

Example: Logical NOT (!)

c
#include <stdio.h>
int main() {
	int isLoggedIn = 0;
	if (!isLoggedIn) {
		printf("Please log in");
	}
	return 0;
}

Short-Circuit Evaluation

C's && and || operators short-circuit: in a && b, if a is already false, b is never evaluated at all, since the overall result is already determined -- this matters when b has side effects or could cause an error if evaluated unnecessarily.

Example: Short-Circuit Evaluation

c
#include <stdio.h>
int main() {
	int a = 0;
	if (a != 0 && (10 / a > 1)) {
		printf("unreachable");
	}
	printf("Safe: division skipped");
	return 0;
}

Combining Logical Operators

Combining several logical operators in one expression without parentheses relies on C's default precedence rules, which can be easy to misjudge -- wrapping each sub-condition in parentheses makes the intended grouping unambiguous at a glance.

Example: Combining Logical Operators

c
#include <stdio.h>
int main() {
	int age = 20;
	int hasTicket = 1;
	if ((age >= 18) && (hasTicket || age >= 65)) {
		printf("Entry allowed");
	}
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.