Reputation: 135
Anyone:
I want to use one macro to print log, following,
#define isaObject(parameter) _Generic((parameter), id: YES, id __strong: YES, default: NO)
#define kNSLog(parameter) do \
{ \
BOOL is = isaObject((parameter)); \
if (is) \
{ \
NSLog(@"----Yes : %@", parameter); \
} \
else \
{ \
NSLog(@"----No : %d", parameter); \
} \
} while (NO)
int i = 99;
NSString * s = @"abcd";
kNSLog(i);
kNSLog(s);
Then, the Compiler gave the warning "Format specifies type 'int' but the argument has type 'NSString *'".
How to modify, Please?
Upvotes: 2
Views: 3787
Reputation: 16
#define isaObject(parameter) _Generic((parameter), id: YES, id __strong: YES, default: NO)
#define kNSLog(parameter) do
{
BOOL is = isaObject((parameter));
if (is)
{
NSLog(@"----Yes : %@", parameter);
}
else
{
NSLog(@"----No : %d", parameter);
}
}
while (NO)
plz use ------>
NSString * s = @"YES";
kNSLog(s);
Upvotes: 0
Reputation: 108151
Well that's pretty easy to debug if you perform the macro replacement "by hand".
kNSLog(s)
expands to
do
{
BOOL is = isaObject((s));
if (is)
{
NSLog(@"----Yes : %@", s);
}
else
{
NSLog(@"----No : %d", s); // the warning is thrown here
}
} while (NO)
You are explicitly checking the type of the parameter, but you didn't inform the compiler about this, so it see that one branch may actually be trying to print an NSString
using a %d
format.
The solution is to explicitly cast the parameter after you check it, so that you provide the compiler with enough information to keep it silent. Specifically
if (is)
{
NSLog(@"----Yes : %@", parameter);
}
else
{
NSLog(@"----No : %d", (int)parameter);
}
Upvotes: 2
Reputation: 22701
You can explicitly cast the parameter to an int
to avoid that warning:
NSLog(@"----No : %d", (int)parameter); \
Upvotes: 6