Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a volatile string as the format string with printf()

Suppose I have the following function signature:

int printf(const char * restrict format, ... );

Now, I have a string defined as follows:

volatile char command_str[256];

Now, when I want to pass this string to my printf function, I will get the following warning:

Warning 32  [N] 2943 : passing 'volatile char [256]' to parameter of type 'const char *' discards qualifiers    C:\P\parameter\parameter.c

I do not want to change the printf signature, the easiest solution to make the warning go away would be

printf((const char*)command_str, .......);

I have a feeling that this is not the best solution. What would be the correct thing to do? I cannot make command_str non-volatile since it is accessed within an interrupt.

like image 751
Tom L. Avatar asked Jul 17 '26 04:07

Tom L.


1 Answers

the const in printf()'s signature declares a promise printf() makes -- it won't mess with the data pointed to by format (therefore, both char* and const char* variables may be passed in for format).

Now, your array is volatile (and I expect you know the implication of that). The compiler warns you, that this volatility is discarded in printf()'s scope -- you won't get volatile semantics for accesses to format within printf().

As a suggestion what to do, I'd say evaluate whether you really want changes to the data be apparent midst- printf(). I can't see a reason for wanting that, so making a local copy sounds reasonable.

like image 79
fstd Avatar answered Jul 18 '26 22:07

fstd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!