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

The addition operator `+`

The addition operator +

What you'll learn: How to use the plus sign to combine numerical values and variables into a single sum.

Simple Math in Code

In C, the plus sign (+) works exactly like it did in your primary school math classes. It is an arithmetic operator used to add two values together. These values can be "literals" (plain numbers like 5 or 10) or variables that hold numbers.

Think of the + operator as a small machine with two input slots. You put a value on the left and a value on the right, and the machine outputs the total. In programming terminology, we call the numbers being added operands.

How it works

When the C compiler sees the + symbol, it calculates the sum of the operands and "replaces" that expression with the result before moving on to the next task.

For example, if you write int total = 10 + 5;, C first calculates 15 and then stores that final number into the variable named total. You can also add a variable to a number, or even two variables to each other.

#include <stdio.h>

int main() {
    int apples = 12;
    int oranges = 8;
    
    // Adding two variables together
    int totalFruit = apples + oranges;
    
    // Adding a literal to a variable
    int extraFruit = totalFruit + 5;
    
    printf("Total fruit: %d\n", totalFruit);
    printf("With extras: %d\n", extraFruit);

    return 0;
}

The "Bucket" Analogy

Imagine you have two buckets of water. One bucket represents the variable apples and the other represents oranges. The + operator is the act of pouring both buckets into a new, larger bucket called totalFruit.

Crucially, using the + operator doesn't change the original values unless you specifically tell it to. After the addition, your apples bucket still technically has "12" in it; you’ve simply used a copy of that value to create a new sum.

Mixing Types

While you will mostly add whole numbers (int), the + operator is versatile. It works just as well with decimals (float or double). If you add an integer to a decimal, C is smart enough to handle the conversion for you, resulting in a precise decimal total.

Key takeaway

The + operator calculates the sum of two operands and is typically used to assign a new value to a variable.