1

I want to define different parameter according to different device, but I got a compiling mistake as below:

#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

#if IS_IPAD                   //invalid token at start of a preprocessor expression
#define defaultHeight 475
#else
#define defaultHeight 175
#endif

I want to know the right grammar for my purpose, thanks!

itenyh
  • 1,921
  • 2
  • 23
  • 38
  • possible duplicate of [#if Check between iphone and ipad](http://stackoverflow.com/questions/3697165/if-check-between-iphone-and-ipad) – rishi Jun 23 '12 at 06:26

2 Answers2

10

You could do:

#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define DEFAULT_HEIGHT ((IS_IPAD) ? 475.0 : 175.0)
gschandler
  • 3,208
  • 16
  • 16
2

You can't do this with the preprocessor. Preprocessor conditional macros only accept compile-time constant expressions. Use C code instead, something like this:

float defaultHeight;
if (IS_IPAD)
{
    defaultHeight = 475;
}
else
{
    defaultHeight = 175;
}

By the way, it's bad practice to give preprocessor #define macros lowercase names. If you want to use a macro for the default height, use

#define DEFAULT_HEIGHT value

instead.

  • 1
    Actually, it's pretty common Apple-ese to use mixed-case macros. Even then, they're still generally given uppercase initial characters (`DefaultHeight`), and usually a prefix (`NSFooBarWidth`) and/or "k" (`kWidgetWeight`, `kCFPotatoCount`) at the beginning. There are exceptions, of course, especially in older (Carbon/Cassic-era) APIs. Apple's a little indecisive that way. – Jonathan Grynspan Jun 23 '12 at 07:08
  • @JonathanGrynspan Yes, and it's pretty annoying that they're often inconsistent with naming... –  Jun 23 '12 at 10:15
  • They're generally consistent within a particular framework. Core Foundation always uses `kCFThisStyle` for instance. At least they're trying to improve things. – Jonathan Grynspan Jun 23 '12 at 10:23
  • 1
    Minor nit: not even all compile-time-constant expressions are valid. The preprocessor works solely with macro definitions. It's not a compiler and doesn't know anything semantic about the code. For example `sizeof(SomeType)` is a compile-time expression, but the preprocessor doesn't know how to make sense of it. You can't use it in a `#if` directive. – Ken Thomases Jun 24 '12 at 03:12