public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* count array elements passed as func arg
@ 2009-01-30 22:47 fkater
  0 siblings, 0 replies; only message in thread
From: fkater @ 2009-01-30 22:47 UTC (permalink / raw)
  To: gcc-help

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}));


^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2009-01-30 22:47 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2009-01-30 22:47 count array elements passed as func arg fkater

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).