C is one of those programming languages that most programmers never predicted would take off. Designed as a highly efficient, somewhat cryptic language used to write an operating system named UNIX, C is a language designed by systems programmers. In the late 1980s, the same decade after its primary release, virtually every program on the store shelves was written in C. C, followed by its successor C++, quickly replaced the popular Pascal language in the 1980s and despite a much broader set of programming languages available today for different development jobs, C and C++ still remain viable programming choices. C’s impact on the programming world cannot be stressed enough.
C++ is considered by many to be a better language than C. C++ offers full support for object-oriented programming (OOP). Whereas you work with objects in Visual Basic, the Visual Basic language is not a true OOP language. You’ll learn in this hour how and why C++ provides strong OOP support and how the mechanics of C++ provide for more flexible, maintainable, and efficient programming than its predecessor, C.
The highlights of this hour include
Understanding why C is so efficient
Recognizing C commands and operators
Outputting with C’s printf()
function
Using C++ to build on C programming skills
Using C++ classes
Using inheritance to decrease programming time
C is highly efficient and C’s developers required that efficiency because until C, programmers used assembly language, a language just above the machine language level, to write operating systems. Only assembly language had the efficiency needed for systems programs. C brought the advantage of a higher level language to the table when developers used C for operating systems. Along with the efficiency of a low-level language, C has the high-level-language advantage of being more maintainable and programmers were more easily able to update the operating system and produce accurate code. Assembly language doesn’t lend itself very well to proper program maintenance.
To achieve its efficiency, C does have one drawback that other high-level languages don’t: C is more cryptic than most other programming languages. Its cryptic nature comes in the form of a huge collection of operators and a small number of keywords. Table 19.1 lists C’s keywords. In the standard C language, there are only 32 keywords, which is an extremely small number compared to other languages, such as Java and PHP.
Caution
Notice that C’s keywords all appear in lowercase. C’s built-in functions also require lowercase names. C is case sensitive so if you use an uppercase letter anywhere inside a keyword or function, your program will not compile properly.
You should recognize some of C’s commands because the JavaScript language that you learned about at the beginning of this tutorial borrows heavily from C and C++.
C has more operators than any other programming language, with the exception of the scientific APL language that is rarely, if ever, used anymore. Of course, languages derived from C, such as Java and C++, often have as many or more operators than C. Because you have already studied Java, you understand many of C’s operators.
To program in C, you need a C compiler. Almost any C compiler you use today is a C++ compiler as well. Therefore, you get two languages for one, although C++ is really just an extension of the C language. In the early days, you often needed to purchase a compiler, usually from Borland or Microsoft. Now, there are a number of options available for free download. These are powerful packages that include an integrated development environment (IDE), compiler, debugger, and other helpful development tools.
If you plan on developing in multiple languages, including C (or C++), Microsoft’s development tools can be an excellent choice, as the IDE for C/C++ is similar to the one for Visual Basic and other .NET languages. Remember that developers created Visual Basic from the beginning to be a Windows programming system. C, on the other hand, began in the world of text-based computers. Therefore, nothing is embedded in the C or C++ programming languages to support a graphical interface.
The program required seven lines to output one simple sentence—and they say C is a more efficient language! Actually, C is an efficient language, but it will take you getting into C and writing more complex programs to really take advantage of the power of C; the language was written by programmers for programmers. With C’s compiled efficiency and power comes the responsibility to master the language and all its nuances.
Listing 19.1 contains three sets of grouping symbols: angled brackets, <>
, braces, {}
, and parentheses, ()
. Be extremely careful when typing a C program because the correct and exact symbol is important. C doesn’t handle ambiguity very well, so if you type the wrong symbol, C won’t work properly.
The cornerstone of every C program is the main()
function. Because main()
is a function and not a command, the parentheses after are required. A C function, just like a JavaScript function, is a section of code that does something. The main()
function is required because execution of a C program always begins in its main()
function. Programmers use main()
to control the rest of the program. The main()
function often includes a series of procedure calls.
The actual code for main()
, as with all C functions (except the built-in functions whose code you never see), begins after the opening brace, {
, and main()
continues until the closing brace, }
, where main()
terminates and other functions often begin. Other sets of braces, always in pairs, may appear within a function such as main()
as well.
As in JavaScript, many of C’s (and C++’s) statements end with a semicolon (;
). The more you work with C, the better you’ll learn which statements require the semicolon and which don’t. Full statements require the semicolon. In Listing 19.1, the line with main()
doesn’t require a semicolon because main()
doesn’t terminate until the final closing brace in the last line. The brace requires no semicolon because it is a grouping character and does nothing on its own.
Note
The next few sections concentrate on the fundamental C language but the material is applicable to C++ also. C++’s strength over C is its ability for OOP as you’ll see later in this hour.
You’ll never see #include
in a list of C commands because #include
is not a C command. Statements in a C program that begin with the pound sign are called preprocessor directives. The compiler analyzes the directive and, instead of compiling the statement, acts upon the statement immediately during compilation.
The #include
preprocessor directive tells the compiler to insert another file that resides in source code form at the location in the program where the directive resides. Therefore, before the program is actually compiled, more code is inserted, at the programmer’s request, at the place where #include
occurs. That code is compiled along with the programmer’s code.
The stdio.h
file is a source code auxiliary file that helps a C program perform input/output (I/O) properly. C files that end with the .H
extension are called header files as opposed to C program source code files that end with the .C
filename extension. All C programs perform some kind of I/O, and the most common header file used to help C with its I/O is stdio.h
. As you learn more about C, you’ll learn additional header files that can be helpful, such as the time.h
header file that includes definitions that help with time and date conversions.
C supports data formats that work much like Java’s data formats. For example, C supports the following kinds of data:
Character
Integer
Floating point (decimal numbers)
C supports several types of integers and floating-point data such as long and short integers as well as single-precision and double-precision floating-point decimal data.
Unlike Java, C does not support a string data type. Although C has some built-in functionality to handle strings in some situations, generally the C language leaves it to the programmer and functions to handle strings. C doesn’t support an intrinsic string data type. Therefore, the only text-based data type that C supports is a single character.
Note
The fact that C doesn’t include support for a built-in string data type isn’t a huge problem because ample built-in functions are available in the language to work with string data. Also, C does allow for string literals, such as strings that you type directly in the code, just not string variables. Unlike Java, however, string data is not inherently supported in the fundamental language, which sometimes makes for some interesting programming.
Listing 19.1 included a string literal as well. String literals (remember there is no string variable) are always enclosed in quotation marks. Therefore, the following are string literals:
"C is efficient"
"3"
"443-55-9999"
Tip
Given the cryptic nature of C, you should add comments to your code as much as possible. You will need the comments when you later make changes to the program. You’ll be happy to know that the style of comments used in C is exactly the same as in JavaScript—enclose comments between /*
and */
or preceded by //
as shown in the statements below:
/* Ask how old the user is */
printf("How old are you? "); // Ask for the age
scanf(" %d", &age); /* Ampersand required */
When you declare variables in C, you need to be more specific of the type of variable you need than in JavaScript. Consider the following section of a main()
function:
main()
{
char initial;
int age;
float amount;
...// more code here
}
This code declares three variables, initial
, age
, and amount
. They hold three different types of data: a character, an integer, and a floating-point value. These variables are local to the function and cannot be used outside main()
. (You can declare variables before main()
and those variables would be global to the whole program, but global variables are not recommended, as you already know.)
The assignment statement works just as it does in JavaScript. You can initialize variables like this:
initial = 'G';
age = 21;
amount = 6.75;
C is built on a foundation of functions—both those functions that you write and the functions supplied by C. The next two sections should help you understand the nature of C functions.
Unlike just about every other programming language in the world, C has no input or output statements. Look through Table 19.1 once more. You don’t see a print
statement or anything else that might be considered an I/O statement.
C performs all its I/O through functions that your C compiler provides. By letting the compiler makers implement I/O in functions, the C language is highly portable, meaning that a C program that runs on one kind of computer should run on any other computer that is capable of running C programs. A C program written for a Macintosh will work on a PC without change, assuming that you compile the program using each computer’s own C compiler.
The most common I/O function is the printf()
function. printf()
outputs data to the screen in most cases (although the programmer can route the output to other devices, if needed, through operating system options). Here is the format for printf()
:
printf(controlString [, data]);
The controlString determines how the output will look. The controlString will format any data values that you specify (separated by commas if more than one value is output) in the data area. Consider the following printf()
:
printf("Read a lot");
This printf()
doesn’t include a data list of any kind. The controlString is the only argument to this printf()
. When you use a string of text for the controlString value, C outputs the text directly to the screen. Therefore, the printf()
produces this onscreen when the user runs the program:
Read a lot
Caution
Just like JavaScript, remember to use the
character if you want output to force the cursor to the next line. If the previous printf()
was followed by this printf()
:
printf("Keep learning");
the output would look like this:
Read a lotKeep learning
Obviously, the second printf()
should have used the
character like this:
printf("Keep learning ");
With
, subsequent printf()
output would appear on the next line.
When you print numbers and characters, you must tell C exactly how to print them. You indicate the format of numbers with conversion characters that format data. The conversion characters format data in functions such as printf()
(see Table 19.2).
When you want to print a value inside a string, insert the appropriate conversion characters in the controlString. Then, to the right of the controlString, list the value you want printed. Figure 19.1 shows how a printf()
can print three numbers—an integer, a floating-point value, and another integer.
Strings and characters have their own conversion characters as well. You don’t need %s
to print strings by themselves because strings included inside the controlString that don’t have the formatting percent sign before them print exactly as you type them. Nevertheless, you might need to use %s
when combining strings with other data.
The next printf()
prints a different type of data value using each of the conversion characters from Table 19.2:
print("%s %d %f %c ", "Sams", 14, -8.76, 'X'),
This printf()
produces this:
Sams 14 –8.760000 X
The string Sams
needs quotation marks, as do all string literals, and the character X
needs single quote marks, as do all characters. C formats the floating-point numbers with full precision, hence the four zeros at the end of the value. You can limit the number of places printed by using format specifiers. If the printf()
’s conversion characters for the floating-point number had been %5.2
, the –8.76
would have been output in five spaces, with two of those five spaces used for the decimal portion. Therefore, the following printf()
printf("%s %d %f %c ", "Sams", 14, -8.76, 'X'),
would yield this output:
Sams 14 –8.76 X