C++ is an extension of the language c, so all of the basic types in c++ are found in c. Some of the commonly used types are int (integer), double (real number), and char (character data). In addition, c++ has a type string (found in cstring.h) with many of the string operations, such as concatenation, commonly found in other languages.
Like c, c++ is a case sensitive language, so int is the designation for integer, while Int is read as a user defined identifier. It is possible (but not recommended) to write
int Int;to create an integer variable Int. Because case sensitivity can lead to errors such as defining an identifier Int and later using int as a variable rather than a type, c++ programmers usually establish conventions for capitalization. While this is no single convention, we will use the following widely accepted conventions.
Other types of identifiers will have conventions introduced when appropriate.
Programs in c++ are created from a group of header and code files. Header files define new types and have a suffix h. Code files have definitions of functions and have the cpp suffix. In all but the simplest programs, more than one code file is used. To group these files Borland c++ programs are created in projects.
Simple c++ programs must contain one file that has a function main defined in it. This function is the main program. For the most part this function will always be defined in a file that looks like this:
#ifndef MYAPP_H
#include "myapp.h"
#endif
void main()
{
Application myApplication;
try{
myApplication.run();
}
catch (char *x)
{
cout << x << endl; //writes an error message if try fails
}
}
This program creates a variable of application type, where your application function run is
similar to the main program in most other languages. If in the course of running this program,
an error is discovered in any of the functions called in run, the program stops and an error
message is printed.
The lines beginning with '#' are compiler directives. The first line, #ifndef MYAPP_H checks to see if the file myapp.h has been compiled already. If it has been compiled the next two lines are ignored. If it has not been compiled, the file is compile. Normally headers only contain declarations, but they may have some inline code -- functions substituted directly into programs rather than called.
Click here to see your first program.Strings were not a standard type in c. They were handled as if they were arrays of char or pointers to char. In either case the last character in the string was always followed by the null character (The character with code 0). We will use strings defined as char buff[255] later in the course, but for now we will use the c++ type string. In this version of Borland c++ the definition of the class string is in the header cstring. The help for this type gives a list of functions available.
We use strings in the second example.