Reputation: 1771
I am programming a module on a microcontoller for interfacing it's EEPROM to receive some user data from there. Since you can not overwrite the EEPROM easily I want to return a const
pointer to const
data.
Now my functions prototype looks like this:
const struct userData const* getEEPROMDataAtIndex(uint32_t uidIndex)
while gcc tells me duplicate 'const' declaration specifier [-Wduplicate-decl-specifier]
. Shouldn't each const I use have a different effect? One to make the pointed-to data immutable, the other for the received pointer not to be retarged?
Upvotes: 2
Views: 1321
Reputation: 67476
const struct userData const*
=> const struct userData *const
It can be used during the initilalisation of the automatic variable:
const struct userData * const foo(void);
void bar(void)
{
const struct userData *const ptr_to_something = foo();
/* some code */
}
Upvotes: -2
Reputation: 25
I suggest using typdef
to type define your return data type. Then in the function declaration you only need to declare the return type as the typedef name.
For example...
typedef struct USER_DATA
{
....
...
};
I think it would simplify things a bit.
what happens if you interchange 'const struct
' ... to 'struct const
'?
Upvotes: -3
Reputation: 401
You seems have some miss understanding about const, for example.
#include <stdio.h>
int main()
{
int a=123, b=456;
const int *pa = &a;
pa = &b; //legal
*pa = 4; //illegal
printf("a=%d\n", a);
return 0;
}
gcc will give an error saying that
x.c: In function ‘main’:
x.c:8:9: error: assignment of read-only location ‘*pa’
*pa = 4;
^
for your purpose, if I understand correctly, you should define the function as
const struct userData * getEEPROMDataAtIndex(uint32_t uidIndex);
//this const declare the returned pointer point to something cannot be changed
then when you initiate your constant pointer by call this function
const struct userData * const myp = getEEPROMDataAtIndex(index);
// ^ this declare the pointer itself (myp) cannot be changed
Hope this helps.
Upvotes: 4
Reputation: 159
You have declared your struct const twice. Since it doesn't make sense to make the pointer const in a return type, just remove one of the const declarations. If you wanted to make the pointer const (which doesn't really make sense in a return type) you would put const after the asterisk.
Upvotes: 5