When compiling the following program in VS2010, VS2008 or MonoDevelop on Windows, I get warning CS0219, "The variable 'y' is assigned but its value is never used".
namespace Problem
{
public class Program
{
private static void Main(string[] args)
{
object x = new object();
int y = 0;
}
}
}
Why is there no warning for x
when compiling in Visual Studio?
Interestingly, I do get CS0219 warnings for x
and y
when compiling in MonoDevelop on Mac OS X.
Solution: If variable <variable_name> or function <function_name> is not used, it can be removed. If it is only used sometimes, you can use __attribute__((unused)) . This attribute suppresses these warnings.
Unused variables are a waste of space in the source; a decent compiler won't create them in the object file. Unused parameters when the functions have to meet an externally imposed interface are a different problem; they can't be avoided as easily because to remove them would be to change the interface.
No nothing is wrong the compiler just warns you that you declared a variable and you are not using it. It is just a warning not an error. While nothing is wrong, You must avoid declaring variables that you do not need because they just occupy memory and add to the overhead when they are not needed in the first place.
To suppress the warning, one can simply name the variable with an underscore ('_') alone. Python treats it as an unused variable and ignores it without giving the warning message.
It turns out that this warning is suppressed when the right-hand-side of the assignment operation is not a compile-time constant.
A since-deleted post on Microsoft's Visual Studio feedback site explained that it's because they had lots of complaints from people who were assigning variables purely so they could see what a method call returned during debugging, and found the warning irritating:
The suppression of the "assigned but never used" warning in this case was motivated by feedback from users who do this:
int Blah(){ // blah BlahBlah(x, y, z) // blah // blah }
"Hey," says the user while debugging, "I wonder what BlahBlah is returning?" But there is no easy way to examine the return value in the debugger, so users very frequently do this:
int Blah() { // blah int temp = BlahBlah(x, y, z) // blah // blah }
and then use the locals or watch window to examine temp. The temp is never used anywhere else in the function, so it produced an irritating "assigned but not read" warning.
I think this is a bit of a shame since:
Anyway, I understand that you can't please everyone.
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