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.

Similar Reads

Methods to Find the Size of an Array without Using sizeof() Operator

Given an array (you don’t know the type of elements in the array), find the total number of elements in the array without using the sizeof() operator. So, we can use the methods mentioned below:...

1. Using Pointer Hack

The following solution is concise when compared to the other solution. The number of elements in an array A can be found using the expression:...

2. Using Macro Function

...

3. Implement Our Own sizeof( )

We can define a macro that calculates the size of an array based on its type and the number of elements....

4. Using Template Function

...

5. Using a Sentinel Value

Using custom user-defined sizeof function which can provide the functionality same as sizeof( )....

6. Using a Class or Struct

...

Contact Us