Suppress Unused Variable Warnings With #pragma unused

In the interest of clean compiles, a warning about an unused variable is welcome. However, should you have a situation that calls for leaving an unused variable in the code, keep reading.

One example where I’ve found this handy is when I have a variable that is a placeholder for something that has yet to be implemented.

Here is how a typical warning looks for an unused variable.

To suppress the warning, add a #pragma as follows:

NSString *tempMsg;
#pragma unused (tempMsg)

The output in Xcode now looks as follows, notice there are no warnings:

You can add more than one variable to the #pragma statement as follows:

NSString *tempMsg;
int flag = 0;
char *ptr;
#pragma unused (tempMsg, flag, ptr)

One reason I find this approach helpful versus commenting out a variable(s), is that I can do a project search for “unused” and get a quick glimpse of code that I need to revisit.

  1. That’s a bad idea. It’s better to comment the variable out. You can use // TODO or something similar to make these places searchable.

    Removing #pragmas needs discipline, uncommenting something not.

  2. While I appreciate that the creation of variables as placeholders is a legitimate thing to do, I question the wisdom of suppressing warnings to give the illusion of a “clean” compile. The warnings serve a purpose and, by suppressing them, you are not cleansing the compile, merely sweeping the dirt under the rug and pretending it’s not there. Why do a search for “unused” when the compilation warning will take you straight to the offending code? If the code is incomplete, the warnings remind you of that. Without them, you are lulled into a false assumption about the state of your code.

  3. The #pragma is helpful for method parameters that you are forced to include because of a protocol, but have no intention of using. For locally defined variables, I agree it’s kinda silly.

  4. I appreciate the comments…

    I personally find the pragma has its place, however, as other reader’s state, it really depends on how it’s used.

    As far as the thought about “a false assumption about the state of your code”, my intention in suppressing warnings is to allow me to focus on the current code, with the understanding that I’ll return and manage the variables that are not used (add the necessary code or remove them). I agree with the consensus, using the pragma as a long term solution to mask unused variables is not a good coding practice.

  5. While I agree these cases are rare, I have a current case where a method is called and returns a value that is unused. Normally, I wouldn’t assign it to a variable (hence no problem), but in this case, I have a logging statement that traces the value…but ONLY when (via compiler preprocessor defines) the logging for that module is turned on. The rest of the time, the unused variable warning is unneeded.

Comments are closed.