Course contentsShow
← C
Lesson 151 of 1,2193. Operators and ExpressionsFree lesson

The subtraction operator `-`

The subtraction operator -

What you'll learn: How to use the minus sign to find the difference between two numbers or variables in your C programs.

The math of "taking away"

In C, the subtraction operator is the hyphen symbol (-). It works exactly like the math you learned in elementary school: it takes the value on the right away from the value on the left.

Think of your computer's memory like a physical wallet. If you start the day with 50andspend50 and spend 12 on lunch, you perform a subtraction to find out what remains. In C, the computer doesn't just calculate the result; it allows you to store that "leftover" value in a new variable or even update an existing one.

How it looks in code

When you use the - operator, you typically place it between two numbers (constants) or two variables. The computer calculates the result immediately and is usually ready to assign that result to a variable using the equals sign.

#include <stdio.h>

int main() {
    int starting_balance = 100;
    int bill = 40;
    int remaining_balance;

    // Subtracting two variables
    remaining_balance = starting_balance - bill;

    // Subtracting a constant from a variable
    int final_amount = remaining_balance - 5;

    printf("You have %d dollars left.", final_amount);

    return 0;
}

Integers vs. Decimals

The subtraction operator is versatile. It doesn't care if you are working with whole numbers (int) or numbers with decimal points (float or double). However, it follows the rules of the data types you give it. If you subtract two integers, you get an integer. If you subtract two floats, you get a precise decimal result.

One handy trick to remember: you can also use the minus sign to represent a negative number directly, such as int temperature = -10;. In this context, it isn't "subtracting" one thing from another; it's simply labeling the value as being below zero. Whether you are calculating a discount or tracking a drop in temperature, the - operator is your go-to tool for finding the difference.

Key takeaway

The - operator subtracts the right-hand value from the left-hand value and can be used with constants, variables, or both.