Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Comparison Operators | Operators
C Basics

book
Comparison Operators

Understanding Comparison Operators

Comparison operators let you evaluate and compare values. One of the trickier aspects of these operators is remembering the correct order or arrangement of the symbols, like determining whether < or = should come first.

Below is a table of commonly used comparison operators:

OperationSymbolUsage Example
Equality==a == b
Inequality!=a != b
Greater than>a > b
Less than<a < b
Greater than or equal to>=a >= b
Less than or equal to<=a <= b

When these operators are used in a program, the outcome will be either true or false. In the context of programming, true is typically represented as 1, and false is represented as 0.

c

Main

copy
#include <stdio.h>

int main()
{
printf("Expression 8 == 7 + 1 is %d\n", 8 == 7 + 1);
printf("Expression 10 != 3 is %d\n", 10 != 3);
printf("Expression 7 > 7 is %d\n", 7 > 7);
printf("Expression 20 >= 19 is %d\n", 20 >= 20 );
printf("Expression 21 <= 21 is %d\n", 20 <= 21 );

return 0;
}
123456789101112
#include <stdio.h> int main() { printf("Expression 8 == 7 + 1 is %d\n", 8 == 7 + 1); printf("Expression 10 != 3 is %d\n", 10 != 3); printf("Expression 7 > 7 is %d\n", 7 > 7); printf("Expression 20 >= 19 is %d\n", 20 >= 20 ); printf("Expression 21 <= 21 is %d\n", 20 <= 21 ); return 0; }

You'll frequently see comparison operators in loops and conditional statements.

Operator Precedence

Grasping the order of operations, or operator precedence, is crucial.

Note

Consider the equation: 2 + 2 * 2. What's your answer? If you thought it's 8, don't worry — you're not alone. Even the course creator has had moments of math confusion.

When it comes to precedence, the increment (++) and decrement (--) operators are evaluated first. This is followed by the multiplication (*) and division (/) operators. Lastly, the addition (+) and subtraction (-) operators are evaluated.

Take this code for instance:

c
int a = 5;
int b = 3;
int c = a * ++b * a-- + 4;

To clarify the order of operations, you can use parentheses. So, the expression:

c
int c = a * ++b * a-- + 4;

Can be more explicitly written as:

c
int c = ((a * (++b)) * (a--)) + 4;

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 4

Fråga AI

expand
ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt