top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Safer determination of static array size in C++

+1 vote
447 views

A lot of programs contain a definition like the following one:

#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a))

If this is applied to a pointer instead of an array, this still compiles and the result is wrong.

I wonder if there is a kludge we can apply to make this fail to compile. Warning about the sizeof(a) / sizeof(*a) construct when a is not of array type might make sense as well.

posted Aug 9, 2013 by Amit Parthsarthi

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

Microsoft offers _countof, available in Visual Studio 2005 and above http://msdn.microsoft.com/en-us/library/ms175773.aspx, because of this problem. A C++ program using _countof will fail to compile under C++ if array is a pointer.

Here's Microsoft's definition:

extern "C++"
{
template 
char (*__countof_helper(UNALIGNED _CountofType
(
#define _countof(_Array) (sizeof(*__countof_helper(_Array)) + 0)
}

In C, it will still produce erroneous results.

answer Aug 9, 2013 by Kumar Mitrasen
+1 vote

Linux kernel does it this way:

/* Force a compilation error if condition is true, but also produce a result (of value 0 and type size_t), so the expression can be used e.g. in a structure initializer (or where-ever else comma expressions aren't permitted). */

#define BUILD_BUG_ON_ZERO(e) (sizeof(char[1 - 2 * !!(e)]) - 1)

/* &a[0] degrades to a pointer: a different type from an array */

#define __must_be_array(a) 
 BUILD_BUG_ON_ZERO(__builtin_types_compatible_p(typeof(a), typeof(&a[0])))

#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
answer Aug 9, 2013 by Jagan Mishra
Similar Questions
0 votes

My array has five elements i.e. integers and when I print sizeof(arr); it gives me 20. I am expecting it to be 5 can someone clarify why it is 20.

+3 votes

Please provide some details on the static class variable, how it works and any example would be great.

+2 votes

Below is the sample code, Where size of a is not defined at the time of compilation,
Then how compiler knows the size of a? If we run the same program in C then compilation will fail.

#include<iostream>
using namespace std;
main()
{
        string a;
        cin>>a;
        cout<<a;
}
...