On 18/10/10 21:15, Ben Pfaff wrote:
> Paul Eggert <egg...@cs.ucla.edu> writes:
> 
>> On 10/18/10 04:53, Pádraig Brady wrote:
>>
>>> /* Like sizeof, except that it treats a variable sized array
>>>    as a pointer rather than determining the size at runtime.  */
>>> #define CT_SIZEOF(x) (__builtin_constant_p(sizeof x) ? sizeof x: sizeof 
>>> (void*))
>>
>> I don't see how this would work.  If x is a variable-sized
>> array, CT_SIZEOF(x) is not a constant expression, according
>> to the C rules, because for A?B:C to be a constant expression,
>> B and C both have to be constant expressions.
> 
> One could use __builtin_choose_expr() to avoid that particular problem:

This is my test program.
I originally used __builtin_choose_expr but
just __builtin_constant_p seems to work.

#include <stdio.h>
#include "verify.h"
int main(int argc, char* argv)
{
    char s[argc];
/* Like sizeof, except that it treats a variable sized array
   as a pointer rather than determining the size at runtime.
   __builtin_choose_expr is available since gcc 3.1  */
//#define CT_SIZEOF(x) __builtin_choose_expr(__builtin_constant_p(sizeof x), \
//                                           sizeof x, sizeof (void*))
#define CT_SIZEOF(x) (__builtin_constant_p(sizeof x) ? sizeof x: sizeof (void*))
    verify_true (CT_SIZEOF (s) == sizeof (void *) || 12 <= CT_SIZEOF (s));
    printf ("%d\n", CT_SIZEOF(s));
}


Reply via email to