6.9. Characters and Strings

Since beginning your sojourn into C, you have made use of many strings. Each main function gets passed an array of strings, for example, and every printf call has at least one string. Discussion of strings was put off until now because they are a bit more difficult to use than other basic data types like int and float.

As you will undoubtedly have guessed, you can create a literal string by simply putting it between double quotation marks. But how do you declare a string variable? This is trickier, because a string variable is actually an array of characters, which have the type char in C.

char variables have a size of 1 byte. They can represent ASCII characters, which include letters and numbers, as well as punctuation. A literal char is a single character between single quotation marks. Here is an example of creating a char variable, and setting it to the letter A:

char cVar = 'A';

A char can also change its value, just like an int or float. You could change the value of cVar later in the program to b, like this:

cVar = 'b';

As with any variable, if you don't want the value of a character variable to change, you can make it constant:

const char constCharVar = 'c';

Because an array is equivalent to a pointer to the first element of the array, and strings are just arrays of chars, strings are usually given the type char*. Here is an example of initializing a string:

char *myString = "Hello, World!";

This string can be printed like this:

printf("%s", ...

Get Beginning Mac OS® X Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.