Page 66 - Programming the Photon Getting Started With the Internet of Things
P. 66
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 include the following:
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.
Initialize with a string constant in quotation marks; the compiler will size the array
to fit the string constant and a terminating null character, Str4.
Initialize the array with an explicit size and string constant, Str5.
Initialize the array, leaving extra space for a larger string, Str6.
Generally, strings are terminated with a null character: ASCII code 0. This allows
functions to tell where the end of a string is. Otherwise, they would continue reading
subsequent bytes of memory that aren’t actually part of the string.
This means that your string needs to have space for one more character than the text
you want it to contain. That is why Str2 and Str5 need to be eight characters, even though
it is only seven—the last position is automatically filled with a null character. Str4 will be
automatically sized to eight characters, one for the extra null. In Str3, we’ve explicitly
included the null character (written ‘\0’).
It is possible to have a string without a final null character (e.g., if you had specified
the length of Str2 as seven instead of eight). This will break most functions that use
strings, so you shouldn’t do it intentionally. If you notice something behaving strangely
(operating on characters not in the string), however, this could be the problem.
Coding Best Practices
The Particle compiler does not pay any attention to how you lay out your code, but it does
require you to write all your code on a single line with a semicolon between each
statement. If you think about how you may read a book, usually the formatting is very
similar—you have your table of contents, chapters, paragraphs, and index.
Formatting code is a personal choice—some like to keep it messy and some like to
keep things neat and tidy with additional commenting between sections. Usually keeping