Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type casting a variable to void? [duplicate]

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.

like image 467
Galaxy Avatar asked Apr 16 '19 06:04

Galaxy


People also ask

Is it possible to cast a variable to void?

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.

How do you cast a variable to a different type?

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).

What is the purpose of casting to a void type?

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.

What is casting in Java with example?

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.


2 Answers

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.

like image 145
Rishikesh Raje Avatar answered Oct 12 '22 23:10

Rishikesh Raje


This can be used to suppress unused variable(s) compilation warning.

like image 43
Sumit Trehan Avatar answered Oct 13 '22 01:10

Sumit Trehan