How to use Macro Function In C++
We can define a macro that calculates the size of an array based on its type and the number of elements.
#define array_size(arr) (sizeof(arr) / sizeof(*(arr)))
- array_size(arr): Name of the macro
- (sizeof(arr): size of entire array in bytes
- sizeof(*(arr)): size of single element in bytes
Dividing the total size of the array by the size of a single element gives the number of elements in the array.
C++ Program to Find the Size of an Array using Macro
C++
// C++ program to find size of // an array using Macro Function #include <bits/stdc++.h> using namespace std; // Defining Macro #define array_size(arr) (sizeof(arr) / sizeof(*(arr))) int main() { int arr[] = { 1, 2, 3, 4, 5, 6 }; int size = array_size(arr); cout << "Number of elements in arr[] is " << size; return 0; } // This code is contributed by Susobhan Akhuli |
Output
Number of elements in arr[] is 6
Complexity Analysis
- Time complexity: O(1)
- Auxiliary space: O(1)
How to Find Size of an Array in C++ Without Using sizeof() Operator?
In C++, generally, we use the sizeof() operator to find the size of arrays. But there are also some other ways using which we can find the size of an array. In this article, we will discuss some methods to determine the array size in C++ without using sizeof() operator.
Contact Us