views:

141

answers:

2

I have a simple function Bar that uses a set of values from a data set that is passed in in the form of an Array of data structures. The data can come from two sources: a constant initialized array of default values, or a dynamically updated cache.

The calling function determines which data is used and should be passed to Bar. Bar doesn't need to edit any of the data and in fact should never do so. How should I declare Bar's data parameter so that I can provide data from either set?

union Foo
{
long _long;
int _int;
}

static const Foo DEFAULTS[8] = {1,10,100,1000,10000,100000,1000000,10000000};
static Foo Cache[8] = {0};

void Bar(Foo* dataSet, int len);//example function prototype

Note, this is C, NOT C++ if that makes a difference;

Edit
Oh, one more thing. When I use the example prototype I get a type qualifier mismatch warning, (because I'm passing a mutable reference to a const array?). What do I have to change for that?

A: 

As you have done - the function takes a pointer to the data (const if it doesn't need to change it)

Then either pass the pointer if you allocated the data with malloc, or the first element if this is a static array.

Martin Beckett
I get a type qualifier mismatch warning when I do that because I'm passing a mutable reference to a const array. How do I get arround that?
CodeFusionMobile
@CSharperWithJava: you get that error because you're currently missing the `const` in the declaration of `Bar`...
psmears
As the others replied - you need to make the pointer arg const if you are passing a constant value (unless you have a particularly forgiving compiler!)
Martin Beckett
@Martin Beckett Nope. My compiler is not very forgiving at all. C18 compiler for a PIC18 embedded application.
CodeFusionMobile
+7  A: 

You want:

void Bar(const Foo *dataSet, int len);

The parameter declaration const Foo *x means:

x is a pointer to a Foo that I promise not to change.

You will be able to pass a non-const pointer into Bar with this prototype.

psmears
I thought that declared a Foo "pointer that could not be changed", not an pointer to a "Foo that could not be changed".
CodeFusionMobile
No - `const Foo *x` means: `*x` is a `const Foo`. To declare the parameter as a pointer that can't be changed (which is far less useful), you'd have to write `Foo * const x` :)
psmears
Thanks for the clarification. As you can see, I write `Foo*` not `*x`, because I think of x as a `Foo*`, not `*x` as a pointer to a `Foo`. It makes keeping track of variables easier but makes things like pointers to `const` quite confusing.
CodeFusionMobile