Is it possible to use #define
in an "if" statement? The following code works, but I get a warning that the macro is being redefined.
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
#define TableViewHeight 916
#define DisplayHeight 1024
#define DisplayWidth 768
}
else {
#define TableViewHeight 374
#define DisplayHeight 480
#define DisplayWidth 320
}
I also tried this, but it didn't work:
#ifdef UIUserInterfaceIdiomPad
#define TableViewHeight 916
#define DisplayHeight 1024
#define DisplayWidth 768
#else
#define TableViewHeight 374
#define DisplayHeight 480
#define DisplayWidth 320
#endif
Any ideas?
Yes, it's possible but it probably doesn't do what you think. Preprocessor directives are interpreted before the results of the preprocessing step are compiled.
This means that all of the preprocessor directives are interpreted, redefining some of the macros, before the remaining code, which will look something like below, is compiled.
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
}
else {
}
In other words, after preprocessing, you just have empty if
and else
bodies.
If you want to change the value of something based on a condition at run time then that something will have to be an genuine object and not just a preprocessor macro. E.g.
extern int TableViewHeight; // defined somewhere else
extern int DisplayHeight; // defined somewhere else
extern int DisplayWidth; // defined somewhere else
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
TableViewHeight = 916;
DisplayHeight = 1024;
DisplayWidth = 768;
}
else {
TableViewHeight = 374;
DisplayHeight = 480;
DisplayWidth = 320;
}