← Back to C Course | Chapter 1: Introduction & Basics | Lesson 13 of 21

C sizeof Operator

The sizeof operator returns the number of bytes a type, variable, array, struct, or expression occupies, evaluated at compile time, essential for writing portable, size-aware C code.

The sizeof Operator

The sizeof operator returns the number of bytes occupied by a type or a variable, evaluated at compile time, and is essential for writing portable code that doesn't assume a fixed size for any type.

Example: The sizeof Operator

c
#include <stdio.h>
int main() {
	int x = 5;
	printf("%zu", sizeof(x));
	return 0;
}

Size of Basic Types

Applying sizeof to basic types like char, int, and double reveals how much memory each one uses on the current system, which can vary between different compilers and platforms.

Example: Size of Basic Types

c
#include <stdio.h>
int main() {
	printf("char: %zu, int: %zu, double: %zu", sizeof(char), sizeof(int), sizeof(double));
	return 0;
}

Size of Arrays

sizeof applied to an array returns the total number of bytes used by every element combined, and dividing that by the size of a single element is the standard technique for computing an array's length in C.

Example: Size of Arrays

c
#include <stdio.h>
int main() {
	int numbers[5] = {1, 2, 3, 4, 5};
	int length = sizeof(numbers) / sizeof(numbers[0]);
	printf("%d", length);
	return 0;
}

Size of Structures

sizeof applied to a struct returns the total memory the structure occupies, which can be larger than the sum of its individual members due to padding the compiler adds for alignment.

Example: Size of Structures

c
#include <stdio.h>
struct Point {
	char label;
	int x;
};
int main() {
	printf("%zu", sizeof(struct Point));
	return 0;
}

sizeof with Expressions

sizeof can be applied directly to an expression rather than just a type or variable, returning the size of whatever type that expression would evaluate to, without actually computing the expression's value at runtime.

Example: sizeof with Expressions

c
#include <stdio.h>
int main() {
	int a = 5;
	printf("%zu", sizeof(a + 1.0));
	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.