C++ and Algorithmic Thinking for the Complete Beginner: Learn to Think Like a Programmer (Part 1 of 5) by Aristides Bouras & Loukia Ainarozidou

C++ and Algorithmic Thinking for the Complete Beginner: Learn to Think Like a Programmer (Part 1 of 5) by Aristides Bouras & Loukia Ainarozidou

Author:Aristides Bouras & Loukia Ainarozidou [Bouras, Aristides]
Language: eng
Format: epub
Published: 2016-02-16T22:00:00+00:00


//This is equivalent to a = a + 1

b = a;

cout << a << endl;

cout << b << endl;

and another one with a post-incrementing operator.

a = 5;

a++;

//This is equivalent to a = a + 1

b = a;

cout << a << endl;

cout << b << endl;

In both examples a value of 6 is assigned to variable b! So, where is the catch? Are

these two examples equivalent? The answer is “yes,” but only in these two examples.

In other cases the answer will likely be “no.” There is a small difference between

them.

Let’s spot that difference! The rule is that a pre-increment/decrement operator

performs the increment/decrement operation first and then delivers the new value.

Chapter 7

Operators

79

A post-increment/decrement operator delivers the old value first and then performs

the increment/decrement operation. Look carefully at the next two examples.

a = 5;

b = ++a;

cout << a << endl;

//Outputs: 6

cout << b << endl;

//Outputs: 6

and

a = 5;

b = a++;

cout << a << endl;

//Outputs: 6

cout << b << endl;

//Outputs: 5

In the first example, variable a is incremented by one and then its new value is

assigned to variable b. In the end, both variables contain a value of 6.

In the second example, the value 5 of variable a is assigned to variable b, and then

variable a is incremented by one. In the end, variable a contains a value of 6 but

variable b contains a value of 5!

Notice: The double slashes after the cout statements indicate that the text that

follows is a comment; thus, it is never executed.

7.6

String Operators

There are two operators that can be used to concatenate (join) strings.

Operator Description

Example

Equivalent to

+

Concatenation

a = "Hi" + " there";

+=

Concatenation assignment

a += "Hello";

a = a + "Hello";

Notice: Joining two separate strings into a single one is called “concatenation.”

The following example displays “What’s up, dude?”

#include <iostream>

using namespace std;

int main() {

string a, b, c;



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.