9

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?

1
  • +1, just because I'm glad there is still some people that don't tag their questions C/C++ and make a difference between the two :D Commented Jun 15, 2010 at 15:20

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I thought that declared a Foo "pointer that could not be changed", not an pointer to a "Foo that could not be changed".
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 :)
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.
0

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.

4 Comments

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?
@CSharperWithJava: you get that error because you're currently missing the const in the declaration of Bar...
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!)
Nope. My compiler is not very forgiving at all. C18 compiler for a PIC18 embedded application.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.