The C language focuses on simplicity. Whereas other programming languages include a large numbers of keywords, the C language consists of a much smaller number of keywords. As a result, creating C compilers is relatively easy compared to creating compilers for other programming languages, which means that C compilers are easy to write for every operating system. This makes it easier to transfer, or port, C programs from one computer to another.
Because the C language consists of relatively few keywords, it lacks features commonly found in other programming languages, such as offering a string data type. To compensate for its relative sparseness of features, most C compilers include a variety of library files that contain pre-written C code that adds these useful features to the C language. The main problem with C compilers is that every C compiler tends to offer different library files, so a C program designed to run on Windows may not run correctly with a different C compiler on Linux.
The C++ language builds on the C language by adding object-oriented features while retaining the C language's hardware access, speed, and portability. Most large and complicated programs, such as operating systems, are written in C++.
Because C/C++ gives complete access to all parts of the computer, a mistake in a C/C++ program can wipe out data off a hard disk or crash the entire operating system of the computer. Writing C/C++ programs may be easy, but understanding and fixing C/C++ programs can be difficult.
Despite these problems, C/C++ is heavily used throughout the computer industry. To understand programming, you must become familiar with the C/C++ programming language.
A C program is divided into multiple functions where each function acts like a separate building block. To identify the starting point of a C program, one function is always designated as the main function. A simple C program looks like this:
main() { printf ("This is a simple C program. "); }
Large C programs consist of multiple functions where each additional function appears defined separate from the main function. In the following example, the separate function is printme
as follows:
main() { printme; } printme () { printf ("This is a simple C program. "); }
In many programming languages, you can define a function inside another function. However in C/C++, you can't do this.
Oftentimes a C program needs to use a feature defined in a separate library, so you may see programs that define a library to add, such as
#include <stdio.h> main() { printf("This is a simple C program. "); }
The structure of a typical C++ program looks similar. The following C++ example includes a C++ library called iostream
and uses elements defined in a standard C++ library called std
:
#include <iostream> using namespace std; int main () { cout << "This is a simple C++ program."; return 0; }
Despite minor differences, C and C++ programs basically consist of a single main function and zero or more additional functions.
To write a comment in C/C++, you have two choices. First, you can use the double slash character so that anything that appears to the right is a comment, such as
#include <iostream> using namespace std; // This is a comment at the beginning of the program int main () { cout << "This is a simple C++ program."; return 0; }
The double slash character is handy for adding a comment to a single line. If you want to write a comment over multiple lines, you can use the /*
and */
characters, such as
/* This C program was written as a simple example to show people how easy C can be to learn. */ #include <stdio.h> main() { printf("This is a simple C program. "); }
When declaring variables in C/C++, you first declare the data type and then the variable name, such as
datatype VariableName;
VariableName
can be any descriptive name. Because C/C++ is a case-sensitive language, it treats SalesTax
as a completely different variable than salestax.
Some programmers use uppercase letters to make variable names easier to find whereas others use all lowercase. To declare multiple variables, cram them all on a single line, separated by a comma, such as
datatype VariableName1, VariableName2, VariableName3;
Unlike other programming languages, C/C++ doesn't support a string data type. Instead, C/C++ offers two alternatives — a character data type and a library.
First, C/C++ offers a character data type, which can hold a single character. Instead of using a string data type, you can use an array of character data types, which is clumsier, but workable. To declare a character data type, use the char
keyword followed by your variable name, such as
char variablename;
To mimic a string data type, declare an array of characters, such as
char arrayname[arraylength];
So if you wanted to create an array that can hold 20 characters, you could do this:
char firstname[20];
A second alternative is to include a library (string) that implements a string data type, such as
#include <string> using namespace std; string stringvariable;
Whole numbers represent integers, such as −59, 692, or 7. A whole number can be positive or negative. The most common type of integer data type is int
and is used as follows:
int variablename;
If you need to restrict a variable to a smaller range of values, you can declare a short int
or a short
variable as follows:
short int smallvariable; short smallvariable;
The long
integer data type is often identical to the regular int
data type.
All integer types (int, short
, and long
) can also be signed or unsigned. Signed data types can represent positive or negative numbers whereas unsigned data types can represent only positive numbers.
To define positive values for an integer variable, you could do this:
unsigned int variablename;
The signed
declaration isn't necessary because
signed long variablename;
is identical to
long variablename;
Table 1-1 shows the range of values common integer data types in C/C++ can hold.
Table VI.1-1. Typical Storage and Range Limitations of C/C++ Integer Data Types
Data Type | Number of Bytes | Range |
---|---|---|
short | 2 | Signed: −32,768 to 32,767 Unsigned: 0 to 65,535 |
int | 4 | Signed: −2,147,483-3,648 to 2,147,483,647 Unsigned: 0 to 4,294,967,295 |
long | 4 or 8 | Signed: −2,147,483,648 to 2,147,483,647 Unsigned: 0 to 4,294,967,295 |
The exact number of bytes and range of all integer data types depends on the compiler used and the operating system, such as whether you're using a 32-bit or a 64-bit operating system. With many compilers, the range of values is identical between int
and long
data types.
Floating point values represent decimal values, such as 3.158 or −9.4106. Just as you can limit the range of integer values a variable can hold, so can you limit the range of floating point values a variable can hold.
The three types of floating data types are float, double, and long double, as shown in Table 1-2.
Table VI.1-2. Typical Floating Point Data Types
Data Type | Number of Bytes | Range |
---|---|---|
Float | 4 | -1.4023 E-45 to 3.4028 E38 |
Double | 8 | -4.9406 E- 324 to 1.7977 E308 |
Long double | 8 or 12 | -4.9406 E- 324 to 1.7977 E308 |
Real numbers (float, double, and long double) are always signed data types (positive or negative). With many compilers, the range of values is identical between double and long double data types.
In the C language, there are no Boolean
data types. Any nonzero value is considered to represent True, and zero represents False. To mimic a Boolean
data type, many C programmers define numeric values for True and False, such as
#define FALSE 0 #define TRUE 1 int flag = FALSE;
Although this is workable, such an approach forces you to create an integer variable to represent a Boolean value. To avoid this problem, C++ offers a special Boolean
data type (like most programming languages), such as
bool variablename;
A C++ Boolean
data type can hold a value of 0
(False) or 1
(True).
The three types of operators used are mathematical, relational, and logical. Mathematical operators calculate numeric results such as adding, multiplying, or dividing numbers, as shown in Table 1-3.
Table VI.1-3. Mathematical Operators
Mathematical Operator | Purpose | Example |
---|---|---|
+ | Addition | 5 + 3.4 |
- | Subtraction | 203.9 - 9.12 |
* | Multiplication | 39 * 146.7 |
/ | Division | 45/ 8.41 |
% | Modula division (returns the remainder) | 35 % 9 = 8 |
Relational operators compare two values and return a True or False value. The six comparison operators available are shown in Table 1-4.
Table VI.1-4. Relational Operators
Relational Operator | Purpose |
---|---|
== | Equal |
!= | Not equal |
< | Less than |
<= | Less than or equal to |
> | Greater than |
>= | Greater than or equal to |
The relational operator in C/C++ is two equal sign symbols (==
) whereas the relational operator in other programming languages is a single equal sign symbol (=
). If you use only a single equal sign to compare two values in C/C++, your program will work but not the way it's supposed to.
Logical operators compare two Boolean values (True or False) and return a single True or False value, as shown in Table 1-5.
Table VI.1-5. Logical Operators
Logical Operator | Truth Table |
---|---|
&& | True && True = True True && False = False False && True = False False && False = False |
|| | True || True = True True || False = True False || True = True False || False = False |
! | !True = False !False = True |
Both C/C++ have a special increment (++
) and a decrement (--
) operator, which simply adds or subtracts 1
to a variable. Typically, adding 1
to a variable looks like this:
j = 5; i = j + 1;
The increment operator replaces the + 1
portion with ++, such as
j = 5; i = ++j;
In the preceding example, the value of i
is j + 1
or 6
, and the value of j
is also 6
.
If you place the increment operator after the variable, such as
j = 5; i = j++;
Now the value of i
is 5
, but the value of j
is 6
.
The decrement operator works the same way except that it subtracts 1
from a variable, such as
j = 5; i = --j;
In the preceding example, the value of i
is j - 1
or 4
, and the value of j
is also 4
.
If you place the decrement operator after the variable, such as
j = 5; i = j--;
Now the value of i
is 5
, but the value of j
is 4
.
Most programming languages use the equal sign to assign values to variables, such as
i = 59;
However, C/C++ also includes combination assignment and mathematical operators, as shown in Table 1-6.
Table VI.1-6. Assignment Operators
Assignment Operator | Purpose | Example |
---|---|---|
+= | Addition assignment | i += 7 (equivalent to i = i + 7) |
-= | Subtraction assignment | i -= 4 (equivalent to i = i - 4) |
*= | Multiplication assignment | i *= y (equivalent to i = i * y) |
/= | Division assignment | i /= 3.5 (equivalent to i = i / 35) |
%= | Modulo assignment | i %= 2.8 (equivalent to i = i % 2.8) |
The simplest branching statement is an IF
statement that only runs one or more commands if a Boolean condition is True, such as
if (condition) { Command; }
To make the computer choose between two mutually exclusive sets of commands, you can use an IF-ELSE
statement, such as
if (condition) { Command; } else { Command; }
Unlike C, C++ includes an IF-ELSEIF
statement, which uses two or more Boolean conditions to choose which of two or more groups of commands to run, such as
if (condition1) { Command; } else if (condition2) { Command; }
Although the IF-ELSE
statement can only give the computer a choice of two groups of commands to run, the IF-ELSEIF
statement can offer the computer multiple groups of commands to run, such as
if (condition1) { Command; } else if (condition2) { Command; } else if (condition3) { Command; }
As an alternative to the IF-ELSEIF
statement, you can also use the SWITCH
statement, such as
switch (expression) { case value1: Command; break; case value2: Command; break; default: Command; }
The SWITCH
statement always needs to include the break
command to tell the computer when to exit the SWITCH
statement.
The preceding SWITCH
statement is equivalent to the following IF-THEN-ELSEIF
statement:
if (expression = value1) { Command; } else if (expression = value2) { Command; } else { Command; }
To check if a variable matches multiple values, you can stack multiple case statements, such as
switch (expression) { case value1: case value2: Command; break; case value3: case value4; Command; break; default: Command; }
The preceding SWITCH
statement is equivalent to the following IF-ELSEIF
statement in C++:
if (expression = value1) || (expression = value2) { Command; } else if (expression = value3) || (expression = value4) { Command; } else { Command; }
A looping statement repeats one or more commands for a fixed number of times or until a certain Boolean condition becomes True.
To create a loop that repeats for a fixed number of times, use the FOR
loop, which looks like this:
for (startvalue; endvalue; increment) { Command; }
If you wanted the FOR
loop to run five times, you could set the Start value to 1
and the End value to 5
, such as
for (i = 1; i <= 5; i++) { Command; }
If you don't know how many times you need to repeat commands, you'll have to use a WHILE
loop, which looks like this:
while (condition) { Command; }
If the condition is True
, the loop runs at least once. If this condition is False
, the loop does not run.
A variation of the WHILE
loop is the DO-WHILE
loop, which looks like this:
do { Command; } while (condition);
The main difference between the two loops is that the WHILE
loop may run zero or more times, but the DO-WHILE
loop always runs at least once.
Somewhere inside a WHILE
and a DO-WHILE
loop, you must have a command that can change the condition from True
to False
; otherwise, the loop will never end, and your program will appear to hang or freeze.
In C/C++, every subprogram is a function that can return a value. The format of a typical function looks like this:
Datatype functionname (Parameter list) { Commands; Return value; }
The three parts of a C/C++ function are
Data type: Defines the type of value the function returns, such as an integer (int
) or a floating point number (float
). If you don't want a function to return a value, declare its data type as void. This makes the function act like a procedure in other programming languages.
Parameter list: Defines any data and their data types that the function needs to work.
Return: Defines a value to return. This value must be the same data type specified right before the function name.
If a function doesn't return a value or require any data, it might look like this:
void myfunction () { Command; }
If the function needs to return an integer value, it might look like this:
int myfunction () { Command; return value; }
In the preceding example, value
represents any integer value.
To accept data, a function needs a parameter list, which simply lists a variable to hold data along with its specific data type, such as an integer or character. To create a function that accepts an integer and a character, you could do something like this:
int myfunction (int mynumber, char myletter) { Command; return value; }
The preceding function accepts two values by value, so the function can change the values of variables in its parameter list, but those changed values won't appear outside that function.
If you want a function to change the values of its parameters, you need to define a parameter list by identifying which variables accept values by reference. To identify values passed by reference, use the & sign, such as
int myfunction (int& mynumber, char myletter) { Command; return value; }
Many C/C++ compilers include libraries that offer data structures, such as stacks or collections. However, three built-in data structures of C/C++ are the structure (sometimes called a record in other programming languages), enumerated variables, and the array.
A structure is a variable that typically holds two or more variables. To create a structure, use the struct
keyword as follows:
struct name { datatype variable; };
The name of a structure can be any descriptive name, such as baseball_ team
or sales_dept
. Inside a structure, you must declare one or more variables. A typical structure might look like this:
struct MyGrades { char grade; int class_number; };
After defining a structure, you can declare a variable to represent that structure, such as
struct MyGrades chemistry;
As a shortcut, you can define a structure and declare a variable to represent that structure as follows:
struct MyGrades { char grade; int class_number; } chemistry;
Enumerated variables act like a list that lets you name a group of items, such as the days of the week, names of people in a group, and so on. A typical enumerated variable list might look like this:
enum name {item1, item2, item3};
So if you wanted to define the names of the days in a work week, you could do the following:
enum weekend {saturday, sunday};
Now you can declare a variable as a weekend
data type, such as:
enum weekend timeoff;
As an alternative, you can define an enumerated list of variables and give them a name at the same time, such as
enum {saturday, sunday} timeoff;
Arrays in C/C++ are known as zero-based arrays, which means that the first element of the array is located at index number 0
, the second element of the array is located at index number 1
, and so on.
To create an array, declare its data type and size, such as
datatype arrayname[size];
The array name can be any descriptive name. The array size defines how many items the array can hold. To create an array that can hold ten integers, you could define an array like this:
int mynumbers[10];
You can create an array and store values in it at the same time by doing the following:
int mynumbers[4] = {23, 8, 94, 102};
This is equivalent to
int mynumbers[4]; mynumber[0] = 23; mynumber[1] = 8; mynumber[2] = 94; mynumber[3] = 102;
Before C++, object-oriented programming was more of an academic exercise that required special programming languages. After C++ appeared, ordinary programmers could use their knowledge of C to use object-oriented programming for practical purposes.
To create an object, you must create a separate class stored in a class file. A typical class looks like this:
class className { public: datatype propertyname; void methodname(); };
The class lists one or more properties and the type of data that property can hold, such as an integer or floating point number. A class also lists one or more method names, which contains code for manipulating an object in some way. The class defines the method name and its parameter list, but the actual code for that method appears outside the class definition, such as
class className { public: datatype propertyname; void methodname(); }; void classname::methodname() { Commands; }
After you define a class, you can create an object from that class by declaring a variable as a new class type, such as
className objectname;
So if you created an animal
class, you could create an object (things_at_the_zoo
) from that class as follows:
animal things_at_the_zoo;
The C++ language allows both single and multiple inheritance. With single inheritance, you can declare a class name and state the class to inherit from with a colon, such as
class className : public classtoinheritfrom { // Code goes here };
To inherit from multiple classes, name each class as follows:
class className : public class1, public class2 { // Code goes here };