How to Work with Character Variables in C Programming

By Dan Gookin

The getchar() and putchar() functions of the C programming languagework with integers, but that doesn’t mean you need to shun the character variable. The char is still a variable type in C. When you work with characters, you use the char variable type to store them.

CHARACTER VARIABLE MADNESS

#include <stdio.h>
int main()
{
  char a,b,c,d;
  a = 'W';
  b = a + 24;
  c = b + 8;
  d = 'n';
  printf("%c%c%c%c",a,b,c,d);
  return(0);
}

Exercise 1: Create a new project, ex0707, using the source code in Character Variable Madness. Build and run the program.

The code declares four char variables at Line 5. These variables are assigned values in Lines 7 through 10. Line 7 is pretty straightforward. Line 8 uses math to set the value of variable b to a specific character, as does Line 9 for variable c. Line 10 uses an escape sequence to set a character’s value, something you can’t type at the keyboard.

All those %c placeholders are stuffed into the printf() statement, but the output is, well, surprising.

Exercise 2: Modify the code for Character Variable Madness so that variables b and c are assigned their character values directly using character constants held in single quotes.

Exercise 3: Modify the source code again so that putchar(), not printf(), is used to generate output.