[computer-go] C++ parameter passing
Stefan Nobis
stefan-ml at snobis.de
Wed Aug 9 14:48:33 PDT 2006
Peter Drake <drake at lclark.edu> writes:
> I'd like to pass a large array by constant reference. I tried this:
> void remove_from_zobrist_hash(BoardState & state, color_t color, const uint64_t &
> zobrist_numbers[][])
Hmmm... my C++ is a bit rusty, but it seems, this is one of the
pitfalls of the declaration syntax (and I hope, I get everythin
right). Especially arrays and references are a bit hairy.
One of the problems: In some cases C++ distinguishes between arrays
and pointers, in some cases not... and references don't make this
easier. If C++ would allow assignment between arrays, the dimensions
would have to match, so
int a[3];
int b[5];
b = a;
would be an error. If we play with references another detail is
imporant: The type precedence. In most cases arrays and pointers are
the same in C++, so
int a[];
int* b;
are quite the same. Where to put the reference sign? If you try
int &a[];
you get an error, because arrays of references, which is what is
declared here, are not allowed in C++. The type declarators like * and
& are part of the type, so the type is 'reference to int' and from
this type are the array elements. What to do? Correct the precedence
with parens:
int (&a)[];
Now the type is a reference to an array of ints. Will this do? No, not
quite. This is a real array type and in this case dimensions are
imporant:
int a[3];
int (&r)[3] = a; // OK, dimensions match
int (&s)[5] = a; // error, dimension mismatch
int (&t)[] = a; // error, dimension mismatch
In C++ it's only allowed not to set the array dimensions, when the
declaration is in fact a pointer declaration (int* === int[]). So in
your case, if you really want a const reference to an array, you have
to specify the dimension:
void f(const int (&x)[dim1][dim2]);
and dim1 and dim2 have to be compile time constants.
> Is there another way to do this?
You may pass it as const pointer, then you have to specify all
dimensions but the first:
void f(const int (*const x)[dim2]);
--
Until the next mail...,
Stefan.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 188 bytes
Desc: not available
Url : http://computer-go.org/pipermail/computer-go/attachments/20060809/b5dc2cfd/attachment.pgp
More information about the computer-go
mailing list