// Array LENGTH - count number of array elements with error generation in case of improper use
#include <stdio.h>
#include <stddef.h>
#ifdef __augmented // @C - augmented version of C programming language
#define LENGTH length // In @C it is defined internal as length
#endif
#ifndef LENGTH
#ifdef _MSC_VER // MSVC-compatible version
#define LENGTH(A) (sizeof(A) / sizeof((A)[0]) + \
sizeof(char[1 - 2*!!(sizeof(A) == sizeof(void*))]) * 0)
#endif
#endif
#ifndef LENGTH
#if defined(__GNUC__) || defined(__clang__) // GCC/Clang typeof-based macro (compiler-specific)
#define LENGTH(A) ( sizeof(A) / sizeof((A)[0]) + \
sizeof(typeof(int[1 - 2*!!__builtin_types_compatible_p(typeof(A), typeof(&(A)[0]))])) * 0 )
//sizeof(struct{int:-(__builtin_types_compatible_p(typeof(A), typeof(&(A)[0])));}))// Variant
#endif
#endif
#ifndef LENGTH
#ifdef __STDC_VERSION__
#if __STDC_VERSION__ >= 201112L
#define LENGTH(A) (_Generic((A) + 0, default: sizeof(A) / sizeof(*(A)) ))
#else
#if __STDC_VERSION__ >= 199901L // C99+ compound literal approach
#define LENGTH(A) (sizeof(A) / sizeof((A)[0]) + \
0 * sizeof(struct{char c[sizeof(A) == sizeof(void*) ? -1 : 1];}) )
#endif
#endif
#endif
#endif
#ifndef LENGTH
#define LENGTH(A) (sizeof(A) / sizeof((A)[0])) // A pointer is seen as an array with length 1!
#endif
int staticArray[] = {1, 2, 3, 4, 5}; // static array with known size at compile-time
int *Pointer = (int *)staticArray; // pointer (could be dynamic or alias to static)
void Test(int fixedArrayParam[5], // declared as fixed-size but decays to pointer
int inferredArrayParam[], // array syntax, but decays to pointer
int *pointerParam, // explicit pointer
int Length) // actual length for dynamically-sized stack array
{
int stackArray[Length]; // Variable Length Array (VLA) on the stack
printf("LENGTH(staticArray) = %d\n", LENGTH(staticArray)); // correct usage
//printf("LENGTH(Pointer) = %d\n", LENGTH(Pointer)); // incorrect usage
//printf("LENGTH(fixedArrayParam) = %d\n", LENGTH(fixedArrayParam)); // incorrect usage
//printf("LENGTH(inferredArrayParam) = %d\n", LENGTH(inferredArrayParam)); // incorrect usage
//printf("LENGTH(pointerParam) = %d\n", LENGTH(pointerParam)); // incorrect usage
printf("LENGTH(stackArray) = %d\n", LENGTH(stackArray)); // correct usage
}
int main(void)
{
Test(staticArray, Pointer, Pointer, 10);
return 0;
}
https://onecompiler.com/c/43sa5q7g9