Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8682009
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T21:39:25+00:00 2026-06-12T21:39:25+00:00

The usual approach to getting an array’s element count in C in something like

  • 0

The usual approach to getting an array’s element count in C in something like this:

#define COUNTOF(arr) (sizeof(arr) / sizeof(arr[0]))

This results in an integral-constant expression, which is a very nice plus as well.

The problem is that it isn’t type-safe: int* i; COUNTOF(i); /* compiles :( */. In practice, this should come up rarely, but for the sake of correctness it would be nice to make this type-safe.


In C++03 this is easy (and in C++11 it’s even easier, left as an exercise for the reader):

template <typename T, std::size_t N>
char (&countof_detail(T (&)[N]))[N]; // not defined

#define COUNTOF(arr) (sizeof(countof_detail(arr)))

This uses template deduction to get N, the size of the array, then encodes that as the size of a type.

But in C we don’t get that language feature. This is the small framework I’ve made:

// if `condition` evaluates to 0, fails to compile; otherwise results in `value`
#define STATIC_ASSERT_EXPR(condition, value) \
        (sizeof(char[(condition) ? 1 : -1]), (value))

// usual type-unsafe method
#define COUNTOF_DETAIL(arr) (sizeof(arr) / sizeof(arr[0]))

// new method:
#define COUNTOF(arr)                            \
        STATIC_ASSERT_EXPR(/* ??? */,           \
                           COUNTOF_DETAIL(arr)) \

What can I put in /* ??? */ to get my desired behavior? Or is this impossible?

I’d further prefer answers work in MSVC (i.e., C89), but for the sake of curiosity any definite answer will do.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T21:39:26+00:00Added an answer on June 12, 2026 at 9:39 pm

    This is my second answer. And it gives two solutions.

    The first solution requires a gcc extension; the OP did say the he’d prefer answers which work in MSVC, but that “any definite answer will do”.

    The second solution steals ideas from the excellent answer by ouah https://stackoverflow.com/a/12784339/318716, and is probably more portable.

    We start with the classic define:

    #define NUMBER_naive(x) ((int)(sizeof(x) / sizeof(x)[0])) // signed is optional
    

    For the first solution, in gcc, you can do a test to determine whether any expression evaluates to an array (or it gives a compile error at (x)[0]); I’ve tested this solution with the 6-year-old gcc 4.1.2:

    #define NUMBER(x) __builtin_choose_expr(                      \
       __builtin_types_compatible_p(typeof(x), typeof((x)[0])[]), \
       NUMBER_naive(x), garbage_never_defined)
    extern void *garbage_never_defined;
    

    The second solution is:

    #define ASSERT_zero(e) (!sizeof(struct{int:!!(e);})) // BUILD_BUG_ON_ZERO()
    #define NUMBER(x) (NUMBER_naive(x) * !ASSERT_zero((void *)&(x) == (x)))
    

    The following is a short test program, on some sample arrays and pointers:

    #include <stdio.h>
    #define ASSERT_zero(e) (!sizeof(struct{int:!!(e);})) // BUILD_BUG_ON_ZERO()
    #define NUMBER_naive(x) ((int)(sizeof(x) / sizeof(x)[0]))
    #define NUMBER(x) (NUMBER_naive(x) * !ASSERT_zero((void*)&(x) == (x)))
    
    int a1[10];
    extern int a2[];
    extern int a3[10];
    int *p;
    int square[10][10];
    
    static void foo(int param[10]) {
    // printf("foo param    %d\n", NUMBER(param));
    }
    static void bar(int param[][10]) {
    // printf("bar param    %d\n", NUMBER(param));
       printf("bar param[0] %d\n", NUMBER(param[0]));
       printf("bar *param   %d\n", NUMBER(*param));
    }
    int main(void) {
       printf("a1 %d\n", NUMBER(a1));
    // printf("a2 %d\n", NUMBER(a2));
       printf("a3 %d\n", NUMBER(a3));
    // printf("p  %d\n", NUMBER(p));
       printf("square  %d\n", NUMBER(square));
       printf("*square %d\n", NUMBER(*square));
       foo(a1);
       bar(square);
       return 0;
    }
    

    This gives:

    a1 10
    a3 10
    square  10
    *square 10
    bar param[0] 10
    bar *param   10
    

    As you can see, I’ve commented out four lines which would not or should not compile, three for the three pointers, and one for the incomplete array type.

    I had a slight problem with the choice of the third arg of __builtin_types_compatible_p(). The gcc manual (correctly) states "Furthermore, the unused expression (exp1 or exp2 depending on the value of const_exp) may still generate syntax errors." So for now I’ve set it to a never-instantiated variable, garbage_never_defined, so for some the four commented-out lines, rather than a compile error, we get a compiler warning and a linker error.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is the usual way for declare a Java array: int[] arr = new
The usual way to assign color box functionality on a link is like this:
The usual pattern for a singleton class is something like static Foo &getInst() {
I'm really looking for a best approach for how to tackle this one. I
I'm trying to install EclipseFP, using the usual Eclipse Install new software approach. However,
Not sure if this is the usual sort of question that gets asked around
I am running into a problem with webservices. My usual approach to development is
In TG1, you could change the logged in user by doing something like: identity.set_current_identity(identity)
So I know there is this question addressing the need for getting the bytes
Does the approach of route matching for child actions differ from usual actions? In

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.