Introduction
Put simply, an operator is able to manipulate or perform operations on a certain value. Just like with data types, in contrast to Python, operators in C are written a lot less intuitively.
For instance, where we would usually use "and" to check if two things were indeed true in Python, C uses the double ampersand, &&, to do the same.
In this article, we'll take a look at a some useful (yet slightly cryptic) operators available to us in C.
Assignment and Arithmetic Operators
assignment ( = )
assigns the new value on the right to the variable on the left
not to be confused with ( == ) which compares two values and either evaluates to true or false
addition ( + )
adds numbers (or potentially characters and strings) together
subtraction ( - )
subtracts numbers from one another
division ( / )
divides numbers
multiplication ( * )
multiplies numbers
modulus ( % )
returns the remainder of a division expression
Shortcut Operators (Syntactic Sugar)
Shortcut operators or "syntactic sugar" are ways to reduce the amount of code written when updating a variable with itself
For instance (assuming x was initialized before):
x = x * 2;
can be rewritten as:
x *= 2;
This shortcut can be applied to any other arithmetic operator too!
/=
+=
-=
%=
If you're incrementing or decrementing a value by exactly 1, C makes this even easier:
x++;
x--;
This is the equivalent of:
x = x + 1;
x = x - 1;
Booleans
While Booleans or bools are not technically a part of the stdio.h library, they can be included using the cs50.h or stdbool.h libraries
Alternatively, C accepts zero as false and every nonzero value as true
Used for comparing values that evaluate to either true or false
Logical Operators
AND ( && )
evaluates to true if both values being compared evaluate to true
if not, expression evaluates to false
#include <stdio.h>
#include <stdbool.h>
int main(void) {
// expression would evaluate to true bc 12 == 12 evaluates to true
// AND 4 == 4 evaluates to true
bool isEqual = (12 == 12) && (4 == 4);
}
OR ( | | )
evaluates to true if one of the two values being compared evaluates to true
if both are false, expression evaluates to false
#include <stdio.h>
#include <stdbool.h>
int main(void) {
// expression would evaluate to false bc 12 == 11 evaluates to false
// AND 4 == 3 evaluates to false
// since neither one of the two expressions is true
bool isOneEqual = (12 == 11) | | (4 == 3);
}
Relational Operators
NOT ( ! )
inverts or negates the value of its operand
ex:
!true evaluates to false, and vice versa
x != 5 checks if x is not equal to 5
These operators do exactly as you would expect them, returning either true or false:
less than ( x < y )
less than or equal to ( x <= y )
greater than ( x > y )
greater than or equal to ( x >= y )
Final Thoughts
Hopefully by the end of this article you have a basic idea of the syntax used to evaluate or update values in C. Thanks for reading!
Comments