Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mdeh

macrumors 6502
Original poster
Jan 3, 2009
345
2
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 x1–x100? Why or why not?
for ( i = 1; i <= 100; ++i )
printx (i);

Code:
#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 :)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.