macdevcenter.com
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Learning Cocoa: Repurposing Variables
Pages: 1, 2

Stringing it all Together

So we understand a little about characters and about arrays, and that together we get strings. But how? Let’s examine a few ways we can more simply make our arrays. The code from the previous snippet is compacted into the following:

int main (int argc, const char * argv[]) {
	int numbers[5] = {67, 79, 67, 79, 65};
	
	//show the data off
	printf("My favorite numbers are %d, %d, %d, %d, %d",
		numbers[0],
		numbers[1],
		numbers[2],
		numbers[3],
		numbers[4]);
	return 0;
}

We can use this curly-bracket formation to make things a little more terse. You can build and run this snippet and see that it does the exact same thing as the previous snippet. Now let’s do a neat trick. Change the format string so the first line of printf looks like this:

printf("My favorite programming environment is %c%c%c%c%c!",

Build and run again and see encoding in action. The computer has taken the integers we’re using and displayed them as characters; we’ve made an array of numbers into a string. To make our lives even simpler than it is with the bracket notation, C gives us the double-quotes format we saw first, and we see again here:

int main (int argc, const char * argv[]) {
	char numbers[] = "COCOA";
	
	//show the data off
	printf("My favorite programming environment is %c%c%c%c%c!",
		numbers[0],
		numbers[1],
		numbers[2],
		numbers[3],
		numbers[4]);
	return 0;
}

The double-quotes format is really just a simple way of making an array of characters that we can use just like any other array. Note that we can even edit the string in code:

int main (int argc, const char * argv[]) {
	char numbers[] = "COCOA";
	numbers[0] = 'S';
	numbers[2] = numbers[4];
	numbers[2] = 'M';

	//show the data off
	printf("My favorite island is %c%c%c%c%c!",
		numbers[0],
		numbers[1],
		numbers[2],
		numbers[3],
		numbers[4]);
	return 0;
}

Cast Off

Before, when we had printf convert integers into characters, we were using what is known as cast. Now let’s using casting to do something interesting with our code. Let’s put main back to where it was before this article, and change countTo():

int main (int argc, const char * argv[]) {
	//Computes our favorite number
	int* favoriteNumber = malloc(sizeof(int));
	*favoriteNumber = (3 * 4) / 2;
	*favoriteNumber = integerForSeedValue(*favoriteNumber + 2);;
	
	/* now let's tell the world
		what our favorite number is! */
	countTo(*favoriteNumber);
	
	free(favoriteNumber);
	return 0;
}

void countTo(int loopsToPerform) {
	char* msg;
	int loopsToGo = loopsToPerform;
	
	if (loopsToGo > 26) {
		msg = "All the letters of the alphabet!\n";
		loopsToGo = 26;
	} else if (loopsToGo < 0) {
		msg = "None of the letters of the alphabet!\n";
		loopsToGo = 0;
	} else {
		msg = "The first %d letters of the alphabet!\n";
	}
	
	printf(msg, loopsToPerform);
	while (loopsToGo) {
		char thisChar = (char) (65 + (loopsToPerform-loopsToGo));
		printf("%c!\n", thisChar);
		--loopsToGo;
	}
	
	printf("Next time won't you cast with me?\n");
}

main is provided for reference; the new stuff is all in countTo.

There are three new things in this snippet; we’ll note the boring ones first.

Notice that we’ve done something slightly different in our first call to printf by passing it a variable instead of a constant string. This is totally fine; the program will use the passed-in string without difficulty. You will actually use this method quite often in your Cocoa programming, because passing in constants makes your program harder to localize, and so you pass in variables instead.

Secondly, note that we use the -- operator again, but now it’s before the variable (prefixed) instead of after (suffixed). Either one works here, where the variable change is all that’s going on. But you can actually use these operators anywhere you’d normally have the variable, and then their behavior is slightly different. When the operator is prefixed, the variable is changed before it is used. When it is suffixed, the variable is changed after it is used. If you have more than one such operator on the same line, you’re probably best off splitting your code across lines.

The last new thing to note is what the snippet is all about: casting. The first line of our while loop contains the cast. That line is declaring a char called thisChar, but the equation it’s using returns an int. To convert into a char, we put the type we want in between some parentheses, and toss that in front of the code that would normally evaluate to be an int.

But how does it know how to translate numbers into letters? Well, it doesn’t, really, and that’s the beauty of the system: what we’re doing here is not translating, we’re just reading the value we already have a little differently. The ones and zeros remain the same, but we can now use them as a char. If the value really can be read that way, great! If not, you see problems: we could just as easily cast to a char*, which the computer would think is a pointer. But when we used that pointer, the computer would look for a char in memory at address 65, and find out that it can’t read kernel space. Crash goes the program.

Casting is incredibly powerful, and can be used to work out neat tricks like the one above (which you should compile and run now), and much more complex tricks that will save you time and effort as you program. However, it is a tool that is easily misused, and must be used with care.

Stringing You On

So we’ve seen how we can massage our string in lots of different ways -- we can print it, change its contents, reconstruct it, and lots of other things to mutate it from one state into another. The thing we can’t do (for now) is make our string longer. That requires a bit more knowledge than we have at present, but we’ll remedy that situation in the next article, when we talk about NULL and all its cousins, and make our first steps toward using Objects, the building blocks of modern programs.

Seth Roby graduated in May of 2003 with a double major in English and Computer Science, the Macintosh part of a three-person Macintosh, Linux, and Windows graduating triumvirate.


Return to the Mac DevCenter