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
You must be logged in to the O'Reilly Network to post a talkback.
Showing messages 1 through 7 of 7.
-
Late Thanks
2009-03-21 12:20:36 WarDrum [Reply | View]
While it's obviously been a few years since anyone has commented here, I just want to state that I have found these tutorials extremely helpful and am grateful for them. Thanks!
-
What happened??
2005-06-09 16:12:23 mGee [Reply | View]
So what happened with this "series"? Why hasn't there been any continuation to the series?
-
These are great
2004-02-22 03:15:12 thisma [Reply | View]
I've been passively working on learning to program using c, objective c, and cocoa for some time now. That is since I got mac os x 10.1 on my computer way back when. Almost all of the things taught here are things that I've gone over a couple of times before. This time however it's going much more quickly and I'm picking up more. Now I'm just passing the edge of my knowledge with the last couple articles.
Please keep these coming they are irreplaceably helpful.
Joshua E Smith
-
32 bits for char?
2004-01-19 00:28:30 anonymous2 [Reply | View]
Regarding char: "the variable stores this new type in the same 32 bits, and now we just read it as a letter instead of as a number." On most systems, char is 8 bits nowadays; does Cocoa differ in this, or was the number wrong?
-
Wrong title
2004-01-16 20:28:45 anonymous2 [Reply | View]
This series of articles really should NOT be titled "Learning Cocoa". It is very misleading.
This article is a C tutorial. Knowledge of C is a pre-requisite for learning Cocoa, just like knowing the alphabet is a pre-requisite for reading Shakespeare. Calling this series "Learning Cocoa" is like calling a kindergarten alphabet class "Reading Shakespeare". -
Wrong title
2004-01-17 15:57:17 anonymous2 [Reply | View]
It is a course about learning COCOA without the prerequisite of knowing C. That ist what it does. First introduce the necessary C.
The full course will hopefully also include the cool stuff of Objective C and the COCOA frameworks.
I like this course, even if it covers untill know only C, because all the other C only books do not cover XCode as a programming environment at all.





