Sujet : Re: int a = a (Was: Bart's Language)
De : david.brown (at) *nospam* hesbynett.no (David Brown)
Groupes : comp.lang.cDate : 20. Mar 2025, 15:57:48
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vrhadc$3e7sn$3@dont-email.me>
References : 1 2 3 4 5 6 7 8 9
User-Agent : Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Thunderbird/102.11.0
On 20/03/2025 10:02, Tim Rentsch wrote:
scott@slp53.sl.home (Scott Lurndal) writes:
I would disagree with this last statement. (void)x is genuinely
useful and has no ill side effects. 'int a = a;' is exactly
the opposite - not useful and has potenial bad side effects.
I concur except that I recommend using (void)&x rather than (void)x,
because (void)&x is safer. If x is volatile qualified, for example,
the expression (void)x actually does something, and must not be
compiled away, whereas (void)&x does not have these properties.
I would recommend knowing which variables are volatile and which are not, so that the issue does not arise.
Casting a volatile variable to void does "something", but what that "something" is is implementation-defined and can vary between compilers. Doing things to volatiles other than clear, simple reads or writes is a risk - the semantics are not fully defined in the C standards, implementations vary, and it is not at all uncommon for implementations to be inconsistent or buggy in that area. This is why C++ has deprecated many uses of volatile objects. So if you actually want to read a volatile variable but ignore the results (as you might well want to do for hardware device registers), it's best to do :
auto dummy = volatile_var;
(void) dummy;
rather than
(void) volatile_var;