C sizeof Operator
In this page:
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
#include <stdio.h>
int main() {
int x = 5;
printf("%zu", sizeof(x));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
printf("char: %zu, int: %zu, double: %zu", sizeof(char), sizeof(int), sizeof(double));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
struct Point {
char label;
int x;
};
int main() {
printf("%zu", sizeof(struct Point));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int a = 5;
printf("%zu", sizeof(a + 1.0));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- C Introduction
- C History & Features
- C Environment Setup
- C First Program
- C Syntax & Structure
- C Statements
- C Comments
- C Keywords & Identifiers
- C Data Types
- C Character Data Type
- C Numeric Data Types
- C Decimal (Floating-Point) Numbers
- C sizeof Operator
- C Extended Data Types
- C Type Conversion
- C Booleans
- C Variables
- C Changing Variable Values
- C Multiple Variables
- C Constants
- C Fixed-Width Integers