Introduction to Characters

The main data types used in C, including numbers, strings, and arrays, will each have its own chapter in this book, but a more basic type, the character, deserves a little discussion as well. Unlike the number types, character variables can be used for non-numeric characters such as letters and punctuation.

Creating a character variable is easy:

char initial;

Assigning values to character variables is only slightly more complicated, requiring the use of single (straight) quotation marks:

char right_answer;
right_answer = 'D';

Notice that a simple char variable contains only a single character. In the next section you'll learn how to make longer chars.

To print the value of a character using the printf() function, you'll need to use the %c marker.

To demonstrate this, you'll add a char variable to the existing C file.

To work with character variables

1.
Open var3.c (Script 2.3) in your text editor or IDE.

2.
After declaring the other two variables, declare a char called gender (Script 2.4):

char gender; /* M or F */

Script 2.4. This application now uses a third variable type for storing the user's gender as a single character.


This creates a single variable of type char. A comment is added indicating the values the variable is expected to take.

3.
After initializing the other two variables, assign a value to gender:

gender = 'F';

Remember that character variables can be assigned only a single character as a value and that this value is placed within single quotation marks.

4.
Add a third print statement for this new variable:

printf ("Your gender was listed as 
 %c.
", gender);

There's nothing terribly new here except for the fact that the %c formatting mark is used as a placeholder for the gender variable.

5.
Save the file as var4.c.

6.
Compile and run the application (Figure 2.5).

Figure 2.5. Character variables—like gender here—can be printed just like numbers.


✓ Tips

  • Strings, a more complex data type, are assigned values using double quotation marks. You'll learn all about those in Chapter 11, “Working with Strings.”

  • The char data type can also be used for small integers because, technically, it's an integer type, storing characters as their ASCII numeric equivalents. For example, the following lines are equivalent:

    char initial = 'J';
    char initial = 74;
    

    Appendix B lists most of the ASCII characters along with their corresponding numeric values.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset