Binary and Unary Operators in C Programming
Binary Operators
Binary operators require two operands for evaluation.
Multiplication (*)
#include <stdio.h>
int main(void) {
int val = 5;
printf("%d\n", val * val);
return 0;
}
Division (/)
Integer division truncates fractional parts.
#include <stdio.h>
int main(void) {
float x = 12 / 6; // yields 2.000000
float y = 3 / 6; // yields 0.000000
printf("%f\n", x);
printf("%f\n", y);
return 0;
}
To obtain a floating-point result, at least one operand must be a floating-point value.
#include <stdio.h>
int main(void) {
float z = 3.0 / 6; // yields 0.500000
printf("%f\n", z);
return 0;
}
Addition (+) and Subtraction (-)
#include <stdio.h>
int main(void) {
int p = 15, q = 7, sum = 0, diff = 0;
sum = p + q;
diff = p - q;
printf("%d\n", sum);
printf("%d\n", diff);
return 0;
}
Modulus (%)
Returns the remainder of integer division. Operands must be integers; sign follows the first operand.
#include <stdio.h>
int main(void) {
int r = 17 % 5; // yields 2
printf("%d\n", r);
return 0;
}
Assignment and Compound Assignment
Assignment chains execute right-to-left but should be avoided for clarity.
x = y = z + 4; // discouraged style
Compound forms combine an operation with assignment.
int m = 8;
m += 5; // equivalent to m = m + 5
m -= 3; // equivalent to m = m - 3
Supported compound operators: +=, -=, *=, /=, %=.
Unary Operators
Unary operators act on a single operand.
Increment (++)
- Pre-increment: increments before yielding the value.
int n = 12;
int k = ++n; // n becomes 13, k is 13
- Post-increment: yields value before incrementing.
int n = 12;
int k = n++; // k is 12, n becomes 13
Decrement (--)
- Pre-decrement: decrements before yielding the value.
int n = 12;
int k = --n; // n becomes 11, k is 11
- Post-decrement: yields value before decrementing.
int n = 12;
int k = n--; // k is 12, n becomes 11
Sign Operators (+, -)
Explicitly denote positive or negative values.
int pos = +25; // same as int pos = 25;
int neg = -pos; // neg is -25
Explicit Type Casting
Forces conversion between types, discarding incompatible parts if necessary.
int t = (int)9.87; // t receives 9
Without casting:
int u = 9.87; // compiler warning due to type mismatch
Statement Terminator (;)
The semicolon marks the end of a statement, separating executable instructions.