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
Well, an "uninitialized" variable is, in fact, not uninitialized as that terminology may suggest; it is just filled with random garbage that happened to be on that memory section. That is to say, uninitialized variables are not special, they just happen to not contain any meaningful value, but they do have a value.
void
is not a type, rather the contrary -- it's the absence of type. Knowing this, casting to it wouldn't make much sense but as it happens, it is allowed; it simply discards the expression being cast.¹²
Now, casting to a void pointer (void*
) is another thing. It's mostly used as a sort of "generics" in C (e.g, the standard qsort
function uses this). Since these pointers are aligned as character ones³ and can be cast to any other pointer type, you can write functions that take void pointers but cast them to their concrete types inside, thus allowing a generic-like function signature (naturally, a whole lot less safe than what you may find in other languages).
Null pointers are essentially void pointers to an integer constant expression of value 0 and have the interesting property of being guaranteed that when cast to concrete pointer types, they will never be considered equal.⁴
Hope this answers your question, if not let me know in the comments :)
¹ From C's standard, section 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.)
² From C++'s standard, section 5.2.9.4:
Any expression can be explicitly converted to type cv void." The expression value is discarded.
³ From C's standard, section 6.3.2.3:
A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
And 6.2.5.27:
A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.
⁴ From C's standard, section 6.3.2.3:
An integer constant expression with the value 0, or such an expression cast to type
void *
, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
2 comment threads