Skip to Content
Course content

94: Integer Arithmetic Helpers: abs, div, labs

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're managing a warehouse. Sometimes, you don't care if a shipment was an "overage" (too many items arrived) or a "shortage" (not enough arrived); you just want to know the magnitude of the error to figure out how much paperwork to file. Whether it's -5 boxes or +5 boxes, the "error" is simply 5. That's your absolute value.

Now, imagine you have a pallet of 53 widgets and you need to pack them into boxes of 10. You need to know two things simultaneously: how many full boxes you can ship, and how many loose widgets are left over. You could do this in two separate steps, but it's more efficient to just "do the division" once and get both answers at the same time.

Stripping the Sign with abs and labs

In C, when we want that "magnitude" regardless of the sign, we use the functions found in <stdlib.h>. For standard integers, you've got abs(). If you're dealing with those massive numbers stored in a long, you use labs().

#include <stdio.h>
#include <stdlib.h>

int main() {
    int shortage = -15;
    long huge_debt = -1234567890123L;

    int magnitude = abs(shortage);
    long total_debt = labs(huge_debt);

    printf("Error magnitude: %d\n", magnitude);     // 15
    printf("Debt magnitude: %ld\n", total_debt);    // 1234567890123
    return 0;
}

I should give you a heads-up on a classic C gotcha here: abs() returns the same type it takes. Because of how two's complement binary works, the most negative number possible (like INT_MIN) doesn't have a corresponding positive number that fits in the same type. If you try to abs() the absolute minimum integer, you'll get undefined behavior. In a real production system, I'd always check if the value is INT_MIN before calling abs() if the data is coming from an untrusted source.

Getting the Quotient and Remainder in One Shot

Usually, you'd use the / operator for the quotient and the % operator for the remainder. But if you're doing both, you're essentially asking the CPU to do the same hard work twice. The div() function (and its cousins ldiv() for longs) solves this by returning a struct called div_t.

The div_t struct is simple; it just contains two members: quot and rem.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int total_widgets = 53;
    int box_size = 10;

    div_t result = div(total_widgets, box_size);

    printf("Full boxes: %d\n", result.quot); // 5
    printf("Leftover widgets: %d\n", result.rem); // 3
    return 0;
}

You might wonder, "Why bother with a struct when I can just use / and %?" On some older architectures or specific embedded chips, the division instruction actually calculates both the quotient and the remainder in a single cycle and stores them in different registers. Using div() tells the compiler it's okay to use that optimization. Modern compilers are incredibly smart and often optimize / and % into a single operation anyway, but using div() makes your intent explicit and keeps your code portable across different levels of hardware optimization.




📋 Practical Task

Building a Budget Variance Calculator

You are tasked with writing a small utility for an accounting app. The program needs to take a "Target Budget" and an "Actual Spend" and calculate the variance.

Write a program that does the following:

  1. Defines two long variables: target_budget and actual_spend.
  2. Calculates the raw difference (actual_spend - target_budget).
  3. Uses labs() to determine the absolute variance (the total amount the budget was off, regardless of over or under).
  4. Uses ldiv() to determine how many full "Quarterly Installments" (divide the absolute variance by 4) the correction would take, and how much the "Remaining Adjustment" would be for the final installment.
  5. Prints the absolute variance, the number of full installments, and the remaining adjustment.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.