← Back to C++ Course | Chapter 1: Introduction & Basics | Lesson 10 of 15

C++ Numeric Data Types

C++ provides integer types (short, int, long, long long) and floating-point types (float, double), each with a different range or precision, chosen based on what kind of number needs to be stored.

Integer Types

C++ provides several integer types -- short, int, long, and long long -- each offering a different range of whole numbers, with int being the standard default choice for most everyday counting and arithmetic.

Example: Integer Types

cpp
#include <iostream>

int main() {
	short small = 100;
	int regular = 100000;
	long big = 100000000L;
	long long huge = 10000000000LL;
	std::cout << small << " " << regular << " " << big << " " << huge << std::endl;
	return 0;
}

Floating-Point Types

Floating-point types, float and double, store numbers with a fractional part, with double offering roughly twice the precision of float at the cost of using more memory.

Example: Floating-Point Types

cpp
#include <iostream>

int main() {
	float f = 3.14f;
	double d = 3.14159265358979;
	std::cout << f << " " << d << std::endl;
	return 0;
}

Choosing int vs float vs double

Choosing between int, float, and double comes down to whether a value is always a whole number, needs decimal precision with limited memory use, or needs the higher precision double provides for most general decimal math.

Example: Choosing int vs float vs double

cpp
#include <iostream>

int main() {
	int quantity = 5;        // always whole
	float weightKg = 2.5f;   // decimal, limited memory
	double preciseValue = 3.14159265358979; // higher precision
	std::cout << quantity << " " << weightKg << " " << preciseValue << std::endl;
	return 0;
}

Number Ranges and Overflow

Every numeric type has a fixed range of representable values, and exceeding that range causes overflow, where the value silently wraps around to an unexpected result instead of raising an error.

Example: Number Ranges and Overflow

cpp
#include <iostream>
#include <climits>

int main() {
	int maxVal = INT_MAX;
	int overflowed = maxVal + 1; // wraps around unexpectedly
	std::cout << maxVal << " " << overflowed << std::endl;
	return 0;
}

Numeric Literals

Numeric literals can be written in decimal, hexadecimal (with a 0x prefix), or octal (with a leading 0) form, and suffixes like L, U, or F tell the compiler which specific type to treat the literal as.

Example: Numeric Literals

cpp
#include <iostream>

int main() {
	int decimal = 255;
	int hex = 0xFF;
	int octal = 0377;
	long big = 100000L;
	std::cout << decimal << " " << hex << " " << octal << " " << big << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.