Note: Before referring to this article, I recommend you to refer to my previous article i.e. ASCII charset.

Variables declared with a char datatype can accommodate any symbol present in the ASCII character set and can be represented with an 8-Bit (1 Byte) integer value also known as an ASCII value.

  • The range of character variables depends upon the type of modifiers (signed & unsigned). We will see them in the upcoming articles.
  • For Signed char, the range is, -128 to +127  (The most significant bit is used to represent the sign).
  • For Unsigned char,  0 to 255 (No sign bit).

Syntax:

A character variable can be declared and initialized using the below syntax.

/* <Datatype> <variable_name> <assignment_operator> <character_constant>; */char character_variable = 'a';
  • In the above example, character_variable  is a ‘variable name’ & char is the keyword that represents the ‘char datatype’.
  • The content between /* */ is treated as comments (Just for the programmer’s understanding ) and will be removed by a pre-processor.

Binary representation:

If we initialize the character variable with the character constant ‘a’, In memory, the value will be stored like this:

Character ‘a’ represents the ASCII integer value 97.

Important rules:

  • A character should be always enclosed in a single quote.
  • By default, char uses a ‘signed’ type modifier.
  • A char variable can store only one character at a time.
  • Every statement must end with a semicolon.
  • The naming convention is very important & the variable name should be relevant to the operation that it is going to perform.
/* Including the "STanDard Input Output" library to use printf function.*/
#include <stdio.h>        
int main()
{

    /* initializing a character variable with 'c' */    
    char alphabet = 'c'; 
    /* printing the character variable on screen. */      
    printf("%c", alphabet);   

    /* returning the status back to the caller. */
    return 0;                 
}

Explanation :

%c is a format specifier used in functions such as printf and scanf to represent the variable of type char. For other Datatypes, we have different Type specifiers.

Categorized in:

Tagged in: