I recently encountered this code, and I'm confused, what is it for?
What does it mean in the C programming language, to type cast a variable to void
data type? What does this accomplish?
If an expression such as a type cast, or an addition is performed, and the result is not immediately assigned to some variable, then that result gets lost. Why should you ever want to do that? It seems like a useless expression.
The code sample:
int main(int argc, char *argv[])
{
/* void unused vars */
(void) argc;
(void) argv;
// more code here
return 0;
}
It seems the author was not using these variables, but why cast them to void
data type? You might as well cast them to int
data type.
The only time I can image casting a variable to void is if the variable is only used inside some #ifdef code, and you want to suppress the warning when the code is not included. @MartinBonner: Yes, casting a variable to void is typically done when the variable is only used in an assert () so would otherwise produce warnings in release builds.
Type casting is used to convert variables from one type to another. The casting operators (int) and (double) can be used to create a temporary value converted to a different data type. Casting a double value to an int causes the digits to the right of the decimal point to be truncated (cut off and thrown away).
Casting to void is used to suppress compiler warnings. The Standard says in §5.2.9/4 says, Any expression can be explicitly converted to type “cv void.”. The expression value is discarded. Share.
Java Type Casting. Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size. byte -> short -> char -> int -> long -> float -> double.
This is to avoid unused variable warnings in some compilers.
Also there is a MISRA rule which states that all function parameters must be used. This method is a workaround for this rule.
This can be used to suppress unused variable(s) compilation warning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With