Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Cast uninitialized variable to (void)
Parent
Cast uninitialized variable to (void)
Is it undefined behaviour to cast an uninitialized variable to (void)?
Example:
int main()
{
int x;
(void)x;
return 0;
}
Post
The following users marked this post as Works for me:
User | Comment | Date |
---|---|---|
Estela | (no comment) | Sep 12, 2022 at 16:32 |
It depends. This boils down to whether or not the expression cast to void
contains any side effects, such as accessing a volatile
-qualified object or modifying any object.
C17 6.3.2.2:
If an expression of any other type is evaluated as a void expression, its value or designator is discarded. (A
void
expression is evaluated for its side effects.)
In your example the cast operand does not contain any side effects so it is simply discarded, meaning that it is safe.
This would not be fine, however:
{
volatile int x;
(void)x; // undefined behavior, lvalue access of local uninitialized variable
}
While this is ok:
{
int x;
(void)(x=1); // well-defined, x is set to 1
(void)function(x); // well-defined, function is called and the result discarded
}
Regarding all the details of when it is undefined behavior to use an uninitialized variable with an indeterminate value, check out this answer: (Why) is using an uninitialized variable undefined behavior? The explanation is not as trivial as "this is always ok" or "this is always UB". The type of the variable matters a lot - plain integers are for example very unlikely to contain trap representations, but floating-point variables or pointers (particularly) may do.
So this is not ok either:
{
int x,y;
(void)(x=y); // undefined behavior, lvalue access of local uninitialized variable y
}
2 comment threads