C
Beginner
1 min read
Logical and Relational Operators
Example
#include <stdio.h>
/* Safe division — short-circuit prevents divide-by-zero */
double safe_div(int a, int b)
{
return (b != 0) ? (double)a / b : 0.0;
}
int main(void)
{
int x = 5, y = 10;
/* Relational operators */
printf("x == y : %d\n", x == y); /* 0 */
printf("x != y : %d\n", x != y); /* 1 */
printf("x < y : %d\n", x < y); /* 1 */
printf("x > y : %d\n", x > y); /* 0 */
printf("x <= 5 : %d\n", x <= 5); /* 1 */
printf("x >= 6 : %d\n", x >= 6); /* 0 */
/* Logical operators with short-circuit */
int *ptr = NULL;
if (ptr != NULL && *ptr > 0) { /* safe — short-circuits */
printf("ptr is valid and positive\n");
} else {
printf("ptr is NULL — no dereference occurred\n");
}
printf("5 || expensive(): %d\n", 1 || (printf("not reached\n"), 0));
/* Ternary operator */
int score = 72;
const char *grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" : "F";
printf("Score %d -> grade %s\n", score, grade);
printf("safe_div(10, 0) = %.2f\n", safe_div(10, 0));
printf("safe_div(10, 3) = %.4f\n", safe_div(10, 3));
return 0;
}