Common array length macro for C?
Here's a better C version (from Google's Chromium project):
#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
It improves on the array[0]
or *array
version by using 0[array]
, which is equivalent to array[0]
on plain arrays, but will fail to compile if array
happens to be a C++ type that overloads operator[]()
.
The division causes a divide-by-zero operation (that should be caught at compile time since it's a compile-time constant expression) for many (but not all) situations where a pointer is passed as the array
parameter.
See Is there a standard function in C that would return the length of an array? for more details.
There's a better option for C++ code. See Compile time sizeof_array without using a macro for details.
Array-size macro that rejects pointers
Linux kernel uses a nice implementation of ARRAY_SIZE
to deal with this issue:
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
with
#define __must_be_array(a) BUILD_BUG_ON_ZERO(__same_type((a), &(a)[0]))
and
#define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))
Of course this is portable only in GNU C as it makes use of two instrinsics:
typeof
operator and __builtin_types_compatible_p
function. Also it uses their "famous" BUILD_BUG_ON_ZERO
macro which is only valid in GNU C.
Assuming a compile time evaluation requirement (which is what we want), I don't know any portable implementation of this macro.
A "semi-portable" implementation (and which would not cover all cases) is:
#define ARRAY_SIZE(arr) \
(sizeof(arr) / sizeof((arr)[0]) + STATIC_EXP(IS_ARRAY(arr)))
with
#define IS_ARRAY(arr) ((void*)&(arr) == &(arr)[0])
#define STATIC_EXP(e) \
(0 * sizeof (struct { int ARRAY_SIZE_FAILED:(2 * (e) - 1);}))
With gcc
this gives no warning if argument is an array in -std=c99 -Wall
but -pedantic
would gives a warning. The reason is IS_ARRAY
expression is not an integer constant expression (cast to pointer types and subscript operator are not allowed in integer constant expressions) and the bit-field width in STATIC_EXP
requires an integer constant expression.
Standard macro to calculate the number of elements in an array
No there is not such a thing!
For better Macro definition check this link directly:
is-there-a-standard-function-in-c-that-would-return-the-length-of-an-array
or common-array-length-macro-for-c
declaring variable length array as macro
if I am right you want something like that :
#define VARIABLE_LENGTH_CHAR_ARRAY(name, size) \
const int size_of_##name = size; \
char name[size_of_##name]
int main()
{
VARIABLE_LENGTH_CHAR_ARRAY(local_char_array, 16);
}
The name of the (now const) variable for the size now depends on the name of the array itself, that minimize the probability to have homonyms
The expansion of that code produced by gcc -E
gives :
int main()
{
const int size_of_local_char_array = 16; char local_char_array[size_of_local_char_array];
}
But to do that it is strange :
- as
__J__ I
think this not helps to make the program readable - else where in your source
size_of_local_char_array
can be used but if you/someone search for its definition it will not be found - the macro produces two statements, and of course in that case it is not possible to group them in a block
{}
, this is dangerous because this is not intuitive. As you can see in your code you added a useless ';' after the use of the macro while a final ';' is already present in the macro definition
How do I determine the size of my array in C?
Executive summary:
int a[17];
size_t n = sizeof(a)/sizeof(a[0]);
Full answer:
To determine the size of your array in bytes, you can use the sizeof
operator:
int a[17];
size_t n = sizeof(a);
On my computer, ints are 4 bytes long, so n is 68.
To determine the number of elements in the array, we can divide
the total size of the array by the size of the array element.
You could do this with the type, like this:
int a[17];
size_t n = sizeof(a) / sizeof(int);
and get the proper answer (68 / 4 = 17), but if the type ofa
changed you would have a nasty bug if you forgot to change
the sizeof(int)
as well.
So the preferred divisor is sizeof(a[0])
or the equivalent sizeof(*a)
, the size of the first element of the array.
int a[17];
size_t n = sizeof(a) / sizeof(a[0]);
Another advantage is that you can now easily parameterize
the array name in a macro and get:
#define NELEMS(x) (sizeof(x) / sizeof((x)[0]))
int a[17];
size_t n = NELEMS(a);
C find static array size (preventing mistakes)
Try this:
#define ASSERT_ARRAY(a) \
sizeof(char[1-2*__builtin_types_compatible_p(__typeof__(a), __typeof__(&(a)[0]))])
#define ARRAY_SIZE(a) \
(ASSERT_ARRAY(a)*0 + sizeof(a)/sizeof((a)[0]))
It is not portable, but works with both gcc
and clang
and has fewer side effects than n.m.'s proposal.
Is there a standard function in C that would return the length of an array?
Often the technique described in other answers is encapsulated in a macro to make it easier on the eyes. Something like:
#define COUNT_OF( arr) (sizeof(arr)/sizeof(0[arr]))
Note that the macro above uses a small trick of putting the array name in the index operator ('[]
') instead of the 0
- this is done in case the macro is mistakenly used in C++ code with an item that overloads operator[]()
. The compiler will complain instead of giving a bad result.
However, also note that if you happen to pass a pointer instead of an array, the macro will silently give a bad result - this is one of the major problems with using this technique.
I have recently started to use a more complex version that I stole from Google Chromium's codebase:
#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
In this version if a pointer is mistakenly passed as the argument, the compiler will complain in some cases - specifically if the pointer's size isn't evenly divisible by the size of the object the pointer points to. In that situation a divide-by-zero will cause the compiler to error out. Actually at least one compiler I've used gives a warning instead of an error - I'm not sure what it generates for the expression that has a divide by zero in it.
That macro doesn't close the door on using it erroneously, but it comes as close as I've ever seen in straight C.
If you want an even safer solution for when you're working in C++, take a look at Compile time sizeof_array without using a macro which describes a rather complex template-based method Microsoft uses in winnt.h
.
Is there any shortcut for array size / length in C?
You can use sizeof(array)/sizeof(*array)
and make a macro.
#define length(array) (sizeof(array)/sizeof(*(array)))
array_length in C
Computing array lengths, in C, is problematic at best.
The issue with your code above, is that when you do:
int array_length(int a[]){
return sizeof(a)/sizeof(int);
}
You're really just passing in a pointer as "a", so sizeof(a)
is sizeof(int*)
. If you're on a 64bit system, you'll always get 2 for sizeof(a)/sizeof(int)
inside of the function, since the pointer will be 64bits.
You can (potentially) do this as a macro instead of a function, but that has it's own issues... (It completely inlines this, so you get the same behavior as your int k =...
block, though.)
Related Topics
How to Reset Std::Cin When Using It
What Do Each Memory_Order Mean
Why Can't I Capture This By-Reference ('&This') in Lambda
Visual Studio 2015 Doesn't Have Cl.Exe
Getting an Accurate Execution Time in C++ (Micro Seconds)
What's Up with the Thousands of Warnings in Standard Headers in Msvc -Wall
Identifying Primitive Types in Templates
How to Properly Uninitialize Openssl
Are Multiple Mutations of the Same Variable Within Initializer Lists Undefined Behavior Pre C++11
Representing Big Numbers in Source Code for Readability
Understanding Recursion to Generate Permutations
How Does the Custom Deleter of Std::Unique_Ptr Work
Reorder Vector Using a Vector of Indices