PDA

View Full Version : Exercise 12 - 8 ( Last one of the chapter!!! )




mdeh
Jan 27, 2009, 12:38 PM
Could I please get some feedback from the group. I see from the other reply to my query, that this type of thing is not used much...but I suppose the experience does give one some new insights into the workings of the language...although not strictly speaking Obj-c I suppose.
I have changed the printf function to NSLog to comply with the authors wish to only use functions already presented in the book. ( I think printf is a holdout from the 1st edition.


Consider the definition of the printint macro from this chapter:

#define printx(n) printf ("%i\n", x ## n)

Could the following be used to display the values of the 100 variables x1x100? Why or why not?
for ( i = 1; i <= 100; ++i )
printx (i);



#import <Foundation/Foundation.h>

#define PRINTINT(var) NSLog(@ "x%i = %i", var, var)
#define PRINTX(n) PRINTINT( x ## n)
#define NAMEVAR(n) int x ## n
#define INITIALIZEVAR(n) NAMEVAR(n) = n



int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

int i;
for ( i = 1; i <= 100; i++){
INITIALIZEVAR(i);
PRINTX(i);
}

[pool drain];
return 0;
}

sample output:

2009-01-27 10:36:47.308 Exercise_2.0_12_8[2969:10b] x1 = 1
2009-01-27 10:36:47.318 Exercise_2.0_12_8[2969:10b] x2 = 2
2009-01-27 10:36:47.319 Exercise_2.0_12_8[2969:10b] x3 = 3
2009-01-27 10:36:47.319 Exercise_2.0_12_8[2969:10b] x4 = 4
2009-01-27 10:36:47.320 Exercise_2.0_12_8[2969:10b] x5 = 5

It feels kind of sloppy to me, and does not exactly comply with the code asked for, but it does seem to work. Anyway, that closes out that chapter!! Yeh :)