Asking a question in C
A condition is an expression that produces true or false. In C those are just numbers, and knowing that explains most beginner bugs with if.
After this lesson
You should be able to
- Write conditions using <, >, <=, >=, ==, !=.
- Combine conditions with &&, ||, and !.
- Explain why = in an if is a bug that still compiles.
True and false are numbers
C has no separate boolean type in the form you need here. A relational expression like marks >= 35 produces 1 when true and 0 when false. Anywhere C wants a condition, it accepts any number: zero means false, and every non-zero value — including negative ones — means true.
This is why if (marks) compiles and means if marks is not zero. It is legal, and it is almost never what a first-year student intended to write.
if (marks >= 35)
printf("Pass\n");
else
printf("Fail\n");The = versus == trap
== asks whether two values are equal. = assigns. Writing if (grade = 'A') stores 'A' into grade, then asks whether 'A' is non-zero — which it always is. The branch runs every single time, and the original value of grade is destroyed.
The compiler usually only warns, because the construct is legal C. Turn warnings on and read them. A habit that helps: when comparing against a constant, some programmers write if ('A' == grade), because if ('A' = grade) is a hard error the compiler cannot ignore.
Combining conditions, and short-circuiting
&& is true only when both sides are true; || is true when at least one is; ! flips a condition. To test a range you need both ends: marks >= 35 && marks <= 100. Writing 35 <= marks <= 100 compiles but is wrong — it computes (35 <= marks), gets 0 or 1, and compares that to 100, which is always true.
C stops evaluating as soon as the answer is settled. In count != 0 && total / count > 5, if count is zero the right side is never evaluated, so the division never happens. This short-circuiting is not an optimisation detail — it is a guarantee you can rely on to guard dangerous operations.
Try it yourself
Read a year and print whether it is a leap year. A leap year is divisible by 4, except centuries, which must be divisible by 400.
Need a hint?
Express it as one condition using %, && and ||.
Check the worked solution
The rule has two ways to qualify: divisible by 4 but not by 100, or divisible by 400. Grouping matters — without the inner parentheses, precedence would misgroup the test. 2000 is a leap year (divisible by 400); 1900 is not (a century not divisible by 400); 2024 is (divisible by 4, not a century).
#include <stdio.h>
int main(void)
{
int year;
printf("Enter a year: ");
scanf("%d", &year);
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
printf("%d is a leap year\n", year);
else
printf("%d is not a leap year\n", year);
return 0;
}Quick check
What does if (n = 5) printf("yes"); do when n was 8?
Why this lesson exists
Syllabus mapping
Control Structures · Conditions · if Statement
Maps to course outcomes CO1, CO2, CO3.