Reputation: 21
I'm using a generic buffer .c/.h file. I want to create an instance that is qualified as volatile to use as a com buffer.
The following code shows the problem, the qualifier is lost?? when passing the buffer address to the member functions.
The code segment uses the 'const' qualifier as an example, I'm assuming 'volatile' would behave in same way. Using Rowley ARM GCC compiler.
typedef struct buff_t {
char buffchar;
int index;
}buff;
void buff_init( buff *thisbuff ) {
thisbuff->buffchar = 'x';
thisbuff->index = 0;
}
int main(void)
{
buff memBuffer;
buff const UARTBuffer;
buff *buff_ptr;
buff_ptr = &memBuffer;
buff_init( buff_ptr ); /* struct elements initialized as expected */
// UARTBuffer.buffchar = 'y'; /* this caught by compiler as error to read-only object */
buff_ptr = &UARTBuffer; /* compile warning: assignment discards 'const' qualifier from pointer target type */
buff_init( buff_ptr ); /* UARTBuffer elements also initialized, expected const??? */
}
Upvotes: 2
Views: 359
Reputation: 16441
Qualifiers are a property of each pointer, separately.
If an object is const
, and you take a non-const
pointer to it, it doesn't make the pointer const
. The compiler may warn you, or you may crash trying to write to it (irrelevant for volatile
), but the pointer won't be treated as const
.
In your case, both buff_ptr
and buff_init
's thisbuff
should have the qualifier.
Upvotes: 2
Reputation: 206566
The code tries to modify a const
structure object through pointer and hence invokes an Undefined Behavior(UB). In short it is invalid code. The only way to avoid such a scenario is not to write code which invokes an UB.
Note that compilers allow you to write such codes and shoot yourself in the foot(rather face) doesn't mean you should.If you have a gun it is your responsibility to use it judiciously.
To mark a variable as volatile
you just need to add the keyword volatile
during its declaration just similar to const
in the program.
Upvotes: 2