count array elements passed as func arg

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi,

with the fantastic __buildin_object_size of gcc-4.3.* I
managed to implicitly count the number of array elements
passed as function args on the fly -- and this without
loosing type checks. See example below, if interested.


However, I look for a way to achive the same with gcc-3.4-*
if possible. Since the port of gcc-4.3* to windows is far
before being ready. And maybe there is another solution
anyway?

Felix


Example (for gcc-4.3 only!):


/* struct with 2 "func args" to be entred later */
typedef struct{
  int    i;
  double d;
} val;


/* struct to keep the args plus len of array */
typedef struct{
  val*  pval;
  int   len; /* gets set by macro */
} array;


/* the demo func to be called
 * here twice with the same array type (quite
 * useless) */
void f(array a1, array a2){
  
  printf("elements %d, int %d, double %lf\n",
    a1.len,          /* 1 element */
    a1.pval[0].i,    /* 1 */ 
    a1.pval[0].d);   /* 1 */

  printf("elements %d, int %d, double %lf\n",
    a2.len,          /* 2 elements */
    a2.pval[0].i,    /* 2 */
    a2.pval[0].d);   /* 2 */

  printf("elements %d, int %d, double %lf\n",
    a2.len,          /* 2 elements */
    a2.pval[1].i,    /* 3 */
    a2.pval[1].d);   /* 3 */
}


/* using __builtin_object_size divided by the
 * sizeof(one element) to get the # of elements */
#define macro(...)\
  ({ val _val[]={__VA_ARGS__};\
  array _array={_val,__builtin_object_size(_val,0)/sizeof(val)};\
  _array;})


/* calling f and passing arrays of different sizes */
f(macro({1,1}),macro({2,2},{3,3}));



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux