AAV
AAV

Reputation: 3803

Which is the best way to suppress "unused variable" warning

There are 3 (which I know) ways to suppress the "unused variable" warning. Any particular way is better than other ?

First

- (void)testString:(NSString *)testString
{
     (void)testString;
}

Second

- (void)testString:(NSString *)__unused testString
{

}

Third

- (void)testString:(NSString *)testString
{
    #pragma unused(testString)
}

Upvotes: 17

Views: 27684

Answers (3)

Nulik
Nulik

Reputation: 7360

If you are compiling with GCC, you can take advantage of attribute extensions to set the 'unused' attribute. Like this:

int somevar __attribute__((unused));

It also works for unused parameter warnings (-Wunused-parameter)

To make it shorter to write I am using this macro:

#define _U_ __attribute__((unused))

And declare like this:

int somevar _U_ ;

Upvotes: 7

justin
justin

Reputation: 104698

This is the approach I use: cross platform macro for silencing unused variables warning

It allows you to use one macro for any platform (although the definitions may differ, depending on the compiler), so it's a very portable approach to express your intention to popular compilers for C based languages. On GCC and Clang, it is equivalent of wrapping your third example (#pragma unused(testString)) into a macro.

Using the example from the linked answer:

- (void)testString:(NSString *)testString
{
    MONUnusedParameter(testString);
}

I've found this approach best for portability and clarity, in use with some pretty large C, C++, ObjC, and ObjC++ codebases.

Upvotes: 8

Owl_Prophet
Owl_Prophet

Reputation: 378

One way to do it is just to assign a variable pointlessly after it is declared For example:

int foo;
foo = 0;

This should suppress the unused variable warning. It is just a pointless assignment.
But otherwise I would agree with ouah, the first method is the most reliable, if you must choose from those three.

Upvotes: -11

Related Questions