vpprof
vpprof

Reputation: 21

C++ Determine the type of a variable and use it within sizeof()

I would like to write a macro in c++ which would give the value 0 to every element of a table. For instance, having declared i thus: int i[10];, the macro fill_with_zeros(i) would produce this effect:

i[0] = 0;

i[1] = 0; and so on.

This is its code:

#define fill_with_zeros(xyz) \
    for(int l = 0 ; l < sizeof(xyz) / sizeof(int) ; l++) \
        xyz[l] = 0;

The problem is that I want it to work with tables of multiple types: char, int, double etc. And for this, I need a function that would determine the type of xyz, so that instead of sizeof(int) I could use something like sizeof(typeof(xyz)).

Similar threads exist but people usually want to print the type name whereas I need to use the name within sizeof(). Is there any way to do it?

Thanks in advance

Upvotes: 2

Views: 1367

Answers (6)

sbi
sbi

Reputation: 224069

Why do you think you need a macro for that? This should work:

// Beware, brain-compiled code ahead!
template< typename T, std::size_t sz >
inline void init(T (&array)[sz])
{
  std::fill( array, array+sz, T() );
}

I'd expect my std lib implementation to optimize std::fill() to call std::memset() (or something similar) on its own if T allows it.

Note that this does not actually zero the elements, but uses a default-constructed object for initialization. This achieves the same for all types that can be zeroed, plus works with many types that cannot.

Upvotes: 8

Praetorian
Praetorian

Reputation: 109119

You should use memset as others have suggested, but if you really want to go the macro route:

#define fill_with_zeros(xyz) \
for(size_t l = 0 ; l < sizeof(xyz) / sizeof(xyz[0]) ; l++) \
    xyz[l] = 0;

Upvotes: 1

Don Reba
Don Reba

Reputation: 14031

The length of an array can be determined as sizeof(xyz) / sizeof(xyz[0]). However, there are already ZeroMemory and memset functions that do what you want.

Upvotes: 2

user539810
user539810

Reputation:

Why not just use std::memset from <cstring>? This is what it was designed for and will in most cases work a lot faster.

int i[10];
memset (i, 0, sizeof (i));

Upvotes: 1

Jesus Ramos
Jesus Ramos

Reputation: 23268

#define fill_with_zeroes(arr) \
    for (int l = 0; l < sizeof(arr) / sizeof(arr[0]); l++) \
        arr[l] = 0;

Alternatively just call memset(arr, 0, sizeof(arr));

I would suggest using memset instead or int i[10] = { 0 };

Upvotes: 1

John Carter
John Carter

Reputation: 55271

Why not just use memset(xyz, 0, sizeof(xyz));?

All-bits 0 = zero for all built-in types (integer and float).

Upvotes: 3

Related Questions