ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How To Program In C++ #1 - C++ Basics

Updated on August 27, 2010

Hi. This is going to be the first of a series of tutorials that I’m hoping to make which will teach you how to program in C++. These tutorials will be split into sections according to the topic(s) and each section will have several parts.

This hub will cover the following topics:

  • 1.1 Introduction To C++

  • 1.2 Variables, Expressions, and Assignment Statements

  • 1.3 Console Input/Output

  • 1.4 Program Style

  • 1.5 Libraries and Namespaces

Now, let’s get started


Origins of C++

• C++ programming can be thought of as the C programming language with added features.

• C was developed by Dennis Ritchie of AT&T Bell Laboratories in the 1970s and it was first used for writing and maintaining the UNIX operating system.

• C eventually became so popular that versions of the language were written for other popular operating systems.

• C is peculiar because it is a high-level language with many of the features of a low-level language.

• Also, C is not as easy to understand as other languages and it doesn’t have many automatic checks that are present in other high-level languages.

• To overcome these and other shortcomings, Bjarne Stroustrup of AT&T Bell Laboratories developed C++ during the 1980s.


A Sample C++ Program

A C++ program is really a function definition for a function named main. When the program is first run, main is invoked and the statements inside the braces, {}, are executed.

The lines:

set things up so that the libraries with console input and output facilities are available to the program.

The line:

says that main is a function with no parameters that returns an int (integer value). Some compilers will allow you to omit the int or replace it with a void, which indicates that a function doesn’t return a value.

The program ends when the following statement is executed:

This ends the invocation of the function main and returns 0 as the function’s value.

Variable declarations in C++ are similar to what they are in other programming languages. The following declares the variable numberOfLanguages:

The type int is one of the C++ types for whole numbers (integers).

If you haven’t programmed in C++ before, then the use of cin and cout for console I/O is likely to be new to you. I will cover that topic in later hubs but the general idea can be seen in this example.

Consider the following 2 lines:

The first line outputs the text within the quotation marks to the screen. The second line reads in a number that the user enters at the keyboard and sets the value of the variable numOfLanguages to this number.

output two strings. The symbol \n is the newline character, which instructs the computer to start a new line of output.


Identifiers

The name of a variable (or other item you might define in a program) is called an identifier. A C++ identifier must start with either a letter or the underscore symbol, and all the rest of the characters must be letters, digits, or the underscore symbol.

The following, for example, are all valid identifiers:

All the above names are legal and would be accepted by the compiler, but the first five are poor choices for identifiers because they’re not descriptive of their use.

None of the following are legal identifiers, and all would be rejected by the compiler:

The first three are not allowed because they don’t start with a letter or underscore. The remaining three are not identifiers because they contain symbols other than letters, digits, and the underscore symbol.

C++ is a case-sensitive language; that is, it distinguishes between uppercase and lowercase letters in the spelling of identifiers.

Hence, the following are three distinct identifiers and could be used to name three different variable:

The convention that is now becoming universal in object-oriented programming is to spell variable names with a mix of upper and lowercase letters (and digits), to always start a variable name with a lowercase letter, and to indicate “word” boundaries with an uppercase letter as illustrated by the following variables:

There is a special class of identifiers, called keywords or reserved words, that have a predefined meaning in C++ and cannot be used as names for variables or anything else. Doing so would be confusing and dangerous and thus should be avoided.

Variables

Every variable in a C++ program must be declared before it is used. When you declare a variable you are telling the computer what kind of data you will be storing in the variable. For example, the following are 2 definitions that might occur in a C++ program:

The first defines the variable numberOfBeans so that it can hold a value of type int and the second declares oneWeight and total Weight to be variables of type double.

C++ has basic types for characters, integers, and floating-point numbers (numbers with a decimal point). The commonly used type for integers is int. The type char is the type for single characters. The commonly used type for floating-point numbers is double. The type bool (short for Boolean) has the values true and false. In addition, the standard library named string provides the type string, which is used for strings of characters.

Each of the integer types has an unsigned version that includes only nonnegative
values.

Assignment Statements

The most direct way to change the value of a variable is to use an assignment statement. In C++ the equal sign is used as the assignment operator. An assignment statement always consists of a variable on the left-hand side of the equal sign and an expression on the right-hand side. An assignment statement ends with a semicolon.

The following are examples of C++ assignment statements:

The first assignment statement sets the value of totalWeight equal to the number in the variable oneWeight multiplied by the number in numberOfBeans. (Multiplication is expressed using the asterisk, *, in C++.) The second assignment statement sets the value of temperature to 98.6. The third assignment statement increases the value of the variable count by 2.

People often refer to lvalue and rvalue in C++. An lvalue is anything that can appear on the left-hand side of an assignment operator (=). An rvalue is anything that can appear on the right-hand side of an assignment operator.

A variable has no meaningful value until a program gives it one. For example, if the variable minimumNumber has not been given a value either as the left-hand side of an assignment statement or by some other means then the following is an error:

This is because minimumNumber has no meaningful value, and so the entire expression on the right-hand side of the equal sign has no meaningful value. A variable like minimumNumber that has not been given a value is said to be uninitialized.

One way to avoid an uninitialized variable is to initialize variables at the same time they are declared. This can be done by adding an equal sign and a value, as follows:

This both declares minimumNumber to be a variable of type int and sets the value of the variable minimumNumber equal to 3.

As another example, the following declares three variables and initializes two of them:

C++ allows an alternative notation for initializing variables when they are declared. This alternative notation is illustrated by the following, which is equivalent to the preceding declaration:

Variable names and other names in a program should at least hint at the meaning or use of the thing they are naming.

A shorthand notation exists that combines the assignment operator (=) and an arithmetic operator so that a given variable can have its value changed by adding, subtracting, multiplying by, or dividing by a specified value.

Assignment Compatibility

As a general rule, you cannot store a value of one type in a variable of another type. For example, most compilers will object to the following:

There are some special cases in which it is permitted to assign a value of one type to a variable of another type. It is acceptable to assign a value of an integer type, such as int, to a variable of a floating-point type, such as type double. For example, the following is both legal and acceptable style:

Values of type bool can be assigned to variables of an integer type (short, int, long). When assigned to a variable of type bool, any nonzero integer will be stored as the value true. Zero will be stored as the value false. When assigning a bool value to an integer variable, true will be stored as 1, and false will be stored as 0.

Literals

A literal is a name for one specific value. Literals are often called constants and they do not change value.

A more complicated notation for constants of type double is called scientific notation or floating-point notation and is particularly handy for writing very large numbers and very small fractions. For instance, 3.67 x 1017, which is the same as

367000000000000000.0

is best expressed in C++ by the constant 3.67e17. The number 5.89 x 10-6, which is the same as 0.00000589, is best expressed in C++ by the constant 5.89e-6.

String constants are placed inside double quotes, while constants of type char are placed inside single quotes. The two kinds of quotes mean different things. In particular, ’A’ and "A" mean different things. ’A’ is a value of type char and can be stored in a variable of type char. "A" is a string of characters.

Escape Sequences

A backslash, \ , preceding a character tells the compiler that the sequence following the backslash does not have the same meaning as the character appearing by itself. Such a sequence is called an escape sequence. Several escape sequences are defined in C++.

The \\ tells the compiler you mean a real backslash, \, not an escape sequence; the \" tells it you mean a real quote, not the end of a string constant.

The ANSI/ISO standard states that unspecified escape sequences have undefined behavior. Thus, you should not use any escape sequences other than those provided by the C++ standard which are given above.

Naming Constants

To mark a variable declaration so that the value of the variable cannot be changed, precede the declaration with the word const (which is an abbreviation of constant). For example:

If the variables are of the same type, it is possible to combine the above lines into one declaration, as follows:

The word const is often called a modifier, because it modifies (restricts) the variables being declared. A variable declared using the const modifier is often called a declared constant. Writing declared constants in all uppercase letters is not required by the C++ language, but it is standard practice among C++ programmers.

Here's a simple program that illustrates the use of the declaration modifier const.

Arithmetic Operators and Expressions

All the arithmetic operators can be used with numbers of type int, numbers of type double, and even with one number of each type. If both operands (that is, both numbers) are of type int, then the result of combining them with an arithmetic operator is of type int. If one or both of the operands are of type double, then the result is of type double. For example, if the variables
baseAmount and increase are of type int, then the number produced by the following expression is of type int:

However, if one or both of the two variables are of type double, then the result is of type double.

You can specify the order of operations in an arithmetic expression by inserting parentheses. If you omit parentheses, the computer will follow rules called precedence rules. For example:

is evaluated by first doing the multiplication and then the addition. Parentheses make the expression easier to read and less prone to programmer error.

Integer and Floating-Point Division

When used with one or both operands of type double, the division operator, /, behaves as you might expect. However, when used with two operands of type int, the division operator yields the integer part resulting from division. In other words, integer division discards the part after the decimal point. So, 10/3 is 3 (not 3.3333…), 5/2 is 2 (not 2.5), and 11/3 is 3 (not 3.6666…). Notice that the number is not rounded.

The operator % can be used with operands of type int to recover the information lost when you use / to do division with numbers of type int. For example, the statements

yield the following output:

When used with negative values of type int, the result of the operators / and % can be different for different implementations of C++. Thus, you should use /and % with int values only when you know that both values are nonnegative.

Type Casting

A type cast is a way of changing a value of one type to a value of another type. C++ has four to six different kinds of casts, depending on how you count them.

The expression

is a type cast. So, if the value of m is 2, the expression static_cast<double>(m) returns the double value 2.0. You may use any type name in place of double to obtain a type cast to another type.

Note that static_cast<double>(n) does not change the value of the variable n. If n has the value 2 before this expression is evaluated, then n still has the value 2 after the expression is evaluated. Also note that when type casting from a floating-point type to an integer type, the number is truncated, not rounded. static_cast<int>(2.9) is 2; it is not 3.

Increment and Decrement Operators

The ++ in the name of the C++ language comes from the increment operator, ++. The increment operator adds 1 to the value of a variable. The decrement operator, --, subtracts 1 from the value of a variable.

The expression n++ first returns the value of the variable n, and then the value of n is increased by 1. For example, consider the following code:

This code will produce the output:

When C++ evaluates this expression, it uses the value that number has before it is incremented, not the value that it has after it is incremented. Thus, the value produced by the expression n++ is 2, even though the increment operator changes the value of n to 3.

If you reverse the order and place the ++ in front of the variable, the order of these two actions is reversed. The expression ++n first increments the value of the variable n and then returns this increased value of n. For example, consider the following code:

This code will produce the following output:

Notice that the two increment operators in n++ and ++n have the same effect on a variable n: They both increase the value of n by 1. If the ++ is before the variable, the incrementing is done
before the value is returned; if the ++ is after the variable, the incrementing is done after
the value is returned.

Everything I have said about the increment operator applies to the decrement operator as well, except that the value of the variable is decreased by 1 rather than increased by 1.


Output Using cout

Using cout, you can output any number of items, each either a string, variable, or more complicated expression. Simply insert a << before each thing to be output. The two < symbols should be typed without any space between them. The arrow notation << is often called the insertion operator. For example:

This statement tells the computer to output two items: the value of the variable numberOfGames and the quoted string " games played.".

You can include arithmetic expressions in a cout statement, as shown by the following example, where price and tax are variables:

Parentheses around arithmetic expressions, such as price + tax, are required by some compilers, so it is best to include them.

New Lines In Output

Formatting For Numbers With A Decimal Point

When the computer outputs a value of type double, the format may not be what you would like. For example, the following simple cout statement can produce any of a wide range of outputs:

If price has the value 78.5, the output might be

or it might be

or it might be output in the following notation

To ensure that the output is in the form you want, your program should contain some sort of instructions that tell the computer how to output the numbers. If you want two digits after the decimal point, use the following magic formula:

If you insert the preceding three statements in your program, then any cout statements that follow these statements will output values of any floating-point type in ordinary notation, with exactly two digits after the decimal point.

You may use any other nonnegative whole number in place of 2 to specify a different number of digits after the decimal point. If you wish to change the number of digits after the decimal point so that different values in your program are output with different numbers of digits, you only need to repeat the last line of the formula.

Output With cerr

The object cerr is used in the same way as cout. The object cerr sends its output to the standard error output stream, which normally is the console screen. This gives you a way to distinguish two kinds of output: cout for regular output, and cerr for error message output.

Input Using cin

You use cin for input more or less the same way you use cout for output. The syntax is similar, except that cin is used in place of cout and the arrows point in the opposite direction.

You can list more than one variable in a single cin statement, as illustrated by the following:

However, the program doesWhen a program reaches a cin statement, it waits for input to be entered from the keyboard. not read the input until the user presses the Return key.

Also, when you use cin statements, the computer will skip over any number of blanks or line breaks until it finds the next input value. Thus, it does not matter whether input numbers are separated by one space or several spaces or even a line break.


Comments

There are two ways to insert comments in a C++ program. In C++, two slashes, //, are used to indicate the start of a comment. All the text between the // and the end of the line is a comment. The compiler simply ignores anything that follows // on a line. If you want a comment that covers more than one line, place a // on each line of the comment. The symbols // do not have a space between them.

Another way to insert comments in a C++ program is to use the symbol pairs /* and */. Text between these symbols is considered a comment and is ignored by the compiler. Unlike the // comments, which require an additional // on each line, the /*-to-*/ comments can span several lines, like so:

It is difficult to say just how many comments a program should contain. The only
correct answer is “just enough”. In general, whenever something is important and not obvious, it merits a comment.


Libraries and include Directives

C++ includes a number of standard libraries. In fact, it is almost impossible to write a C++ program without using at least one of these libraries. The normal way to make a library available to your program is with an include directive which has the form:

Compilers (preprocessors) can be very fussy about spacing in include directives. Thus, it is safest to type an include directive with no extra space: no space before the #, no space after the #, and no spaces inside the <>.

An include directive is simply an instruction to include the text found in a file at the location of the include directive. A library name is simply the name of a file that includes all the definition of items in the library.

Namespaces

A namespace is a collection of name definitions. All the standard libraries we will be using place their definitions in the std (standard) namespace. To use any of these definitions in your program, you must insert the following using directive:

If you want to make some, but not all, names in a namespace available to your program, there is a form of the using directive that makes just one name available. if the only names from the std namespace that your program uses are cin, count, and endl, you might start your program with the following:

instead of

Summary

  • C++ is case sensitive. For example, count and COUNT are two different identifiers.
  • Use meaningful names for variables.
  • Variables must be declared before they are used. Other than following this rule, a variable declaration may appear anyplace.
  • Be sure that variables are initialized before the program attempts to use their value.
  • This can be done when the variable is declared or with an assignment statement before the variable is first used.
  • You can assign a value of an integer type, like int, to a variable of a floating-point type, like double, but not vice versa.
  • Almost all number constants in a program should be given meaningful names that can be used in place of the numbers. This can be done by using the modifier const in a variable declaration.
  • Use enough parentheses in arithmetic expressions to make the order of operations clear.
  • The object cout is used for console output.
  • A \n in a quoted string or an endl sent to console output starts a new line of output.
  • The object cerr is used for error messages. In a typical environment, cerr behaves the same as cout.
  • The object cin is used for console input.
  • In order to use cin, cout, or cerr, you should place the following directives near the beginning of the file with your program:

  • There are two forms of comments in C++: Everything following // on the same line is a comment, and anything enclosed in \* and *\ is a comment.
  • Do not overcomment.

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)