Language | Libraries | Comparison

string

Description

Strings in the C programming language are defined as arrays of type char.

String declarations

All of the following are valid declarations for strings.

  char Str1[15];
  char Str2[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o'};
  char Str3[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o','\0'};
  char Str4[ ] = "arduino";
  char Str5[8] = "arduino";
  char Str6[15] = "arduino";

Possibilities for declaring strings

  • Declare an array of chars without initializing it as in Str1
  • Declare an array of chars (with one extra char) and the compiler will add the required null character, as in Str2
  • Explicitly add the null character, Str3
  • Initialization is in the form of a string constant in quotation marks, the compiler will size the array to fit the constant and add the extra null, Str4
  • Initialize the array with an explicit size, Str5
  • Initialize the array, leaving extra space for a larger string, Str6

Null termination

Note the differences between Str2 & Str3, in theory it seems the array of Str1 should be able to be contained with a declaration of 7 elements in the array, since there are only 7 letters in "Arduino". However the Arduino language enforces "null termination" meaning that the last character of an array must be a null (denoted by \0), as in Str2.

When declaring a string, you must declare an extra character for this null or the compiler will complain with an error about the initialization string being too long. For the same reasons, Str3 can hold only 14 characters, not 15, as one might assume.

Single quotes or double quotes?

Strings are always defined inside double quotes ("Abc") and characters are always defined inside single quotes('A').

Reference Home

Corrections, suggestions, and new documentation should be posted to the Forum.