Вопрос

I have following macro in my PCH file.

#ifdef DEBUG
    #define MYLOG(...) NSLog(__VA_ARGS__)
#else
    #define MYLOG(...) MYSERVERLOG(MYObject.enableLogging, __VA_ARGS__)
#endif

#define MYSERVERLOG(iLog, ...) iLog ? NSLog(__VA_ARGS__) : TRUE

Now, no matter if I put DEBUG=0 or DEBUG=1, it always go in first clause. But if I use "if" instead of "ifdef" for DEBUG in PCH then it works fine but then I get warnings on all my MYLOG statements saying "Expressing results unused".

How can I get rid of this situation?

Это было полезно?

Решение

I am guessing you only get the warning if DEBUG=0. The problem is that, after running through the preprocessor, the compiler sees code like this:

...
MYObject.enableLogging ? NSLog(@"your log",...) : TRUE;
...

The compiler is fine with letting you ignore the results of a function, assuming that the function did whatever you wanted and the result isn't useful. However, when you go through the trouble of calculating a value in your code with the ternary operator, it expects that you want the result of that calculation. If you know that you will never use the result of this macro, you can cast it to void to ignore it:

#define MYSERVERLOG(iLog, ...) ((void)(iLog ? NSLog(__VA_ARGS__) : TRUE))

If you might use the results of the macro, then you will have to do the cast every time you use the macro and ignore the result, or live with the warnings. In this case, you should still put parentheses around your macro to avoid possible problems.

#define MYSERVERLOG(iLog, ...) (iLog ? NSLog(__VA_ARGS__) : TRUE)

Другие советы

if you do a

#define DEBUG 0

OR if you do a

#define DEBUG 1

the "DEBUG" macro is defined so...

#ifdef DEBUG 

will always be true since DEBUG is defined.

If you want to get into the 2nd clause, you will have to make sure the macro is not defined AT ALL (i.e. Delete the macro or comment it out).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top