What is a trigraph in c ?

Listen to the article
1.0x
00:00

A trigraph in C is formed of three characters, the first two characters are interrogation marks ??, and the last character is just a regular character.

ISO 646, standardized ASCII, and made national variants of it. The national variants differed from ASCII, in the way they represented 10 characters, including the 9 characters, that the C standard provided an alternative way of input for, by using trigraphs .

So, on a keyboard that does not have these 9 characters, or have other characters defined at their places, trigraphs can be used as a way for inputing these characters.

There are nine trigraphs in C , and they are:

Trigraph sequenceCharacter
??<{
??>}
??([
??)]
??!|
??/\
??'^
??-~
??=#

Trigraphs can be used anywhere in a C source file, so they can be used in strings, and characters literals, and they can also be used in the C source code. Trigraph replacement is done early on in the compilation process, so it is done before preprocessing.

  1. /*        
  2. trigraph.c
  3.     a Trigraph is simply formed of two interrogation marks
  4.     followed by a letter . They  are :
  5.         ??< {
  6.         ??> }
  7.         ??( [
  8.         ??) ]
  9.         ??! |
  10.         ??/ \
  11.         ??' ^
  12.         ??- ~
  13.         ??= #
  14. */

  15. ??=include <stdio.h>

  16. int main( int argc, char * argv[ ] )
  17. ??<
  18.     int anIntArray??(3??) = ??< 2 , 3 , 5 ??>;
  19.     printf("anIntArray[0] is : %d ??/n", anIntArray[0]);
  20.     return 0;
  21. ??>

  22. /* Output:
  23. anIntArray[0] is : 2 .*/

gcc can be used to compile a C source file, that contains trigraphs, by using this command:

  1. gcc trigraph.c -trigraphs -Wno-trigraphs

What follows is another example of using trigraphs, and how to escape a trigraph.

  1. #include <stdio.h>

  2. int main( int argc, char  * argv[ ] )
  3. {
  4.     char *cpDoubleQuote = "??/"";
  5.     /* ??\ will be replaced by \ ,
  6.        so you end up with \",
  7.        which is " .*/

  8.     printf( "*cpDoubleQuote is %s\n", cpDoubleQuote );
  9.     // *cpDoubleQuote is "

  10.     char *cpT = "??/??/t";
  11.     /* ??\ will be replaced by \
  12.        ??\ will be replaced by \
  13.        We end up with \\t, so
  14.        \\ is \, so we end up
  15.        with \t .*/

  16.     printf( "*cpT is %s\n" , cpT );
  17.     // *cpT is \t

  18.     printf("%s", "\??(\n");
  19.     /* Placing a backslash before,
  20.        the first interrogation mark,
  21.        does not escape the trigraph.
  22.        Output:
  23.        [
  24.     */

  25.     printf( "%s", "?\?(\n" );
  26.     /* Placing a backslash after
  27.        the second interrogation
  28.        mark, escapes the trigraph.
  29.        Output:
  30.        ??(
  31.     */
  32.     return 0; }