Reviewing basic C++ language syntax
In this section, we will briefly review basic C++ syntax. We’ll assume that you are either a C++ programmer with non-OO programming skills, or that you’ve programmed in C, Java, or a similar strongly typed checked language with related syntax. You may also be a long-standing professional programmer who is able to pick up another language’s basics quickly. Let’s begin our brief review.
Comment styles
Two styles of comments are available in C++:
- The
/* */
style provides for comments spanning multiple lines of code. This style may not be nested with other comments of this same style. - The
//
style of comment provides for a simple comment to the end of the current line.
Using the two comment styles together can allow for nested comments, which can be useful when debugging code.
Variable declarations and standard data types
Variables may be of any length, and may consist of letters, digits, and underscores. Variables are case sensitive and must begin with a letter or an underscore. Standard data types in C++ include the following:
int
: To store whole numbersfloat
: To store floating point valuesdouble
: To store double precision floating point valueschar
: To store a single characterbool
: For boolean values oftrue
orfalse
Here are a few straightforward examples using the aforementioned standard data types:
int x = 5; int a = x; float y = 9.87; float y2 = 10.76f; // optional 'f' suffix on float literal float b = y; double yy = 123456.78; double c = yy; char z = 'Z'; char d = z; bool test = true; bool e = test; bool f = !test;
Reviewing the previous fragment of code, note that a variable can be assigned a literal value, such as int x = 5;
or that a variable may be assigned the value or contents of another variable, such as int a = x;
. These examples illustrate this ability with various standard data types. Note that for the bool
type, the value can be set to true
or false
, or to the opposite of one of those values using !
(not).
Variables and array basics
Arrays can be declared of any data type. The array name represents the starting address of the contiguous memory associated with the array’s contents. Arrays are zero-based in C++, meaning they are indexed starting with array element[0]
rather than array element[1]
. Most importantly, range checking is not performed on arrays in C++; if you access an element outside the size of an array, you are accessing memory belonging to another variable, and your code will likely fault very soon.
Let’s review some simple array declarations (some with initialization), and an assignment:
char name[10] = "Dorothy"; // size is larger than needed float grades[20]; // array is not initialized; caution! grades[0] = 4.0; // assign a value to one element of array float scores[] = {3.3, 4.3, 4.0, 3.7}; // initialized array
Notice that the first array, name
, contains 10 char
elements, which are initialized to the seven characters in the string literal "Dorothy"
, followed by the null character ('
\0'
). The array currently has two unused elements at the end. The elements in the array can be accessed individually using name[0]
through name[9]
, as arrays in C++ are zero-based. Similarly, the array above, which is identified by the variable grades
, has 20 elements, none of which are initialized. Any array value accessed prior to initialization or assignment can contain any value; this is true for any uninitialized variable. Notice that just after the array grades
is declared, its 0th element is assigned a value of 4.0
. Finally, notice that the array of float
, scores
, is declared and initialized with values. Though we could have specified an array size within the []
pair, we did not – the compiler is able to calculate the size based upon the number of elements in our initialization. Initializing an array when possible (even using zeros), is always the safest style to utilize.
Arrays of characters are often conceptualized as strings. Many standard string functions exist in libraries such as <cstring>
. Arrays of characters should be null-terminated if they are to be treated as strings. When arrays of characters are initialized with a string of characters, the null character is added automatically. However, if characters are added one by one to the array via assignment, it would then be the programmer’s job to add the null character ('\0'
) as the final element in the array.
In addition to strings implemented using arrays of characters (or a pointer to characters), there is a safer data type from the C++ Standard Library, std::string
. We will understand the details of this type once we master classes in Chapter 5, Exploring Classes in Detail; however, let us introduce string
now as an easier and less error-prone way to create strings of characters. You will need to understand both representations; the array of char
(and pointer to char
) implementations will inevitably appear in C++ library and other existing code. Yet you may prefer string
in new code for its ease and safety.
Let’s see some basic examples:
// size of array can be calculated by initializer char book1[] = "C++ Programming"; char book2[25]; // this string is uninitialized; caution! // use caution as to not overflow destination (book2) strcpy(book2, "OO Programming with C++"); strcmp(book1, book2); length = strlen(book2); string book3 = "Advanced C++ Programming"; // safer usage string book4("OOP with C++"); // alt. way to init. string string book5(book4); // create book5 using book4 as a basis
Here, the first variable book1
is declared and initialized to a string literal of "C++ Programming"
; the size of the array will be calculated by the length of the quoted string value plus one for the null character ('\0'
). Next, variable book2
is declared to be an array of 25
characters in length, but is not initialized with a value. Next, the function strcpy()
from <cstring>
is used to copy the string literal "OO Programming with C++"
into the variable book2
. Note that strcpy()
will automatically add the null-terminating character to the destination string. On the next line, strcmp()
, also from <cstring>
, is used to lexicographically compare the contents of variables book1
and book2
. This function returns an integer value, which can be captured in another variable or used in a comparison. Lastly, the function strlen()
is used to count the number of characters in book2
(excluding the null character).
Lastly, notice that book3
and book4
are each of type string
, illustrating two different manners to initialize a string. Also notice that book5
is initialized using book4
as a basis. As we will soon discover, there are many safety features built into the string
class to promote safe string usage. Though we have reviewed examples featuring two of several manners to represent strings (a native array of characters versus the string class), we will most often utilize std::string
for its safety. Nonetheless, we have now seen various functions, such as strcpy()
and strlen()
, that operate on native C++ strings (as we will inevitably come across them in existing code). It is important to note that the C++ community is moving away from native C++ strings – that is, those implemented using an array of (or pointer to) characters.
Now that we have successfully reviewed basic C++ language features such as comment styles, variable declarations, standard data types, and array basics, let’s move forward to recap another fundamental language feature of C++: basic keyboard input and output using the <iostream>
library.