Our Guide to the C++ Operator

We find ourselves adding, subtracting, and comparing things on a regular basis. These simple (or complex) operations are just as important in code. In C++, operators perform calculations and compute results. We rely on operators for tasks such as calculating areas and volumes of shapes, comparing values in an if/else statement and checking if a statement is true or false.

What Is an Operator?

Operators are symbols that are used as shortcuts to perform specific mathematical and logical computations on variables and constants in code. Without operators, C++ developers would have a tough time calculating. There are several types of C++ operators that each perform different operations.

Arithmetic Operators

These are the C++ operators designed to perform simple math functions in code. For the most part, the symbols and their corresponding uses should not come as a surprise. C++ supports the following arithmetic operators:

OperatorDescription
+Adds two operands together
Subtracts two operands
*Multiplies two operands together
/Divides one operand by another
%Returns the remainder of a division
++Increases the value of a variable by 1
Decreases the value of a variable by 1

Simple, right? Let’s see how this would look in code:

#include <iostream>using namespace std;int main () {
  int x = 20;
  int y = 10;
  cout << "x + y is " << x + y << endl;
  cout << "x - y is " << x - y << endl;
  cout << "x * y is " << x * y << endl;
  cout << "x / y is " << x / y << endl;
  cout << "x % y is " << x % y << endl;
  cout << "x++ is " << x++ << endl;
  cout << "x-- is " << x-- << endl;
  return 0;
}

This code would return the following:

x + y is 30
x - y is 10
x * y is 200
x / y is 2
x % y is 0
x++ is 21
x-- is 19

These operators can be used for performing calculations on any number of values.

Assignment Operators

Assignment operators take arithmetic operators in C++ to the next level. These operators allow for the assignment of values to variables. In fact, these simplified operators perform an arithmetic operation on two variables, and the solution assigns the value to the variable on the left. Keep in mind that the values and variables must belong to the same data set.

Here are the most common assignment operators in C++:

OperatorDescriptionEquivalent Equation
=This is the basic assignment operatorx = 2
+=Add and assignment operatorx += y is equal to x = x + y
-=Subtract and assignment operatorx -= y is equal to x = x – y
*=Multiply and assignment operatorx *= y is equal to x = x * y
/=Divide and assignment operatorx /= y is equal to x = x / y
%=Modulus and assignment operatorx %= y is equal to x = x % y

Let’s give these variables some values and see how assignment operators work in code:

int main () {
  int x = 10;
  int y = 5;
  x += y;
  cout<<"x += y is "<<x<<endl;
  x -= y;
  cout<<"x -= y is "<<x<<endl;
  x *= y;     
  cout<<"x *= y is "<<x<<endl;
  x /= y;     
  cout<<"x /= y is "<<x<<endl;
  x %= y;     
  cout<<"x %= y is "<<x<<endl;
  return 0;
}

Here’s what the code would return:

x += y is 15
x -= y is 5
x *= y is 50
x /= y is 2
x %= y is 0

Don’t forget that these values would be assigned to “x” and take the place of the previously assigned value.

Relational Operators

Next up are relational operators. These C++ operators allow programmers to compare two values. If a comparison is true, the program will return true. Relational operators are often used in “if” statements. If one value is greater than, less than or equal to another value, then perform the function located in the “if” statement. If the comparison is not true, you’ll need to tell the code to output something else.

OperatorDescription
==Checks to see if values are equal to each other
!=Checks to see if values are not equal to each other
>Checks to see if the value on the left is greater than the value on the right
<Checks to see if the value on the left is less than the value on the right
>=Checks to see if the value on the left is greater than or equal to the value on the right
<=Checks to see if the value on the left is less than or equal to the value on the right

Below we’ll give you some examples of relational operators as used in C++. See if you can determine what each if/else statement will return.

int main(){
  int x = 25;
  int y = 10;
  if (x==y) {
      cout<<"x and y are the same"<<endl;
  }
  else{
      cout<<"x and y are not the same"<<endl;
  }
  if( x != y ){
      cout<<"x and y are not the same"<<endl;
  }
  else{
      cout<<"x and y are the same"<<endl;
  }
  if( x > y ){
      cout<<"x is greater than y"<<endl;
  }
  else{
      cout<<"x is not greater than y"<<endl;
  }
  if( x < y ){
      cout<<"x is less than y"<<endl;
  }
  else{
      cout<<"x is not less than y"<<endl;
  }
  if( x >= y ){
      cout<<"x is greater than or equal to y"<<endl;
  }
  else{
      cout<<"x is less than y"<<endl;
  }

  if( x <= y){
      cout<<"x is less than or equal to y"<<endl;
  }
  else{
      cout<<"x is greater than y"<<endl;
  }
  return 0;
}

Can you follow all the logic in the program? Here’s what these if/else statements will return using the values assigned to “x” and “y” above:

x and y are not the same
x and y are not the same
x is greater than y
x is not less than y
x is greater than or equal to y
x is greater than y

Logical Operators

We use logical C++ operators to check if statements are true. In their simplest form, logical operators can be used with Boolean variables to determine if a condition is true or not. This is often seen in loops where the program will stay in the loop until the condition returns true or false.

Logical operators can also be used to return true or false in statements with relational, assignment or even arithmetic operators. Let’s first take a look at the three operators and then see how they are used:

OperatorDescription
&&Logical AND operator — returns true if both operands are true
||Logical OR operator — returns true if at least one of the conditions are true
!Logical NOT operator — returns the opposite of the result (if the condition is true, the logical NOT returns false)

By default, these operators will return a 1 if the condition is met and a 0 if it’s not. They can also be used in if/else statements to output different results depending on whether the condition is true.

Let’s put together what we’ve learned thus far and see how logical operators are used in code:

int main() {
  int x = 5;
  int y = 3;
  int z = 6;
  if (x > y && y < z) {
    cout << "x is greater than y and y is less than z"<<endl;  }
  else{
    cout << "At least one of these comparisons returned false"<<endl;  }
  if (x == y || y != z) {    cout << "x is equal to y or y is not equal to z"<<endl;  }
  else{
    cout << "x is not equal to y and y is equal to z"<<endl;  }  if (!(x -= y)) {    cout << "x minus y is zero"<<endl;  }
  else{
    cout << "x minus y is not zero"<<endl;  }  return 0;
}

The program expertly crunches through the data and evaluates the logical operators. Here’s what it returns for each if/else statement:

x is greater than y and y is less than z
x is equal to y or y is not equal to z
x minus y is not zero

Some of these examples are certainly more useful than others!

Bitwise Operators

Bitwise C++ operators perform operations on a bit-by-bit basis, with a bit referring to a single binary digit. These operators take integer-type values, transform them into their binary counterparts and then perform an operation on them. They are typically used for setting, testing and shifting bits.

Let’s take a look at which operators we’re dealing with:

Operator Description
&Bitwise AND — takes two numbers and performs an AND on each bit of the two numbers. The individual bits will be set to 1 if corresponding bits in both operands are 1 and a 0 otherwise.
|Bitwise OR — takes two numbers and performs an OR on each bit of the two numbers. The operation will return 1 if at least one of the bits is a 1 and a 0 otherwise.
^Bitwise XOR — takes two numbers and performs an XOR on each bit of the two numbers. The operation will return 1 if the two bits are different and a 0 if they are the same.
<<Left shift operator — takes a number and shifts each bit a specified number of spaces to the left. Excess bits are discarded. Vacant bits to the right are replaced with a 0.
>>Right shift operator — takes a number and shifts each bit a specified number of spaces to the right. Excess bits are discarded. Vacant bits at the left are replaced with a 0.
~Bitwise NOT — inverts all the bits of a number.

Notice a lot of similarities to the operators we covered above. Be careful not to mix them up or you may throw your code for a loop. Speaking of code, here’s how these operators look:

int main() {
  int x = 12; // 0000 1100 in binary
  int y = 22; // 0001 0110 in binary
cout << "x & y = " << (x & y) << endl;
cout << "x | y = " << (x | y) << endl;
cout << "x ^ y = " << (x ^ y) << endl;
cout << "Inversion of x is " << (~x) << endl;
cout << "Shift bits in x left 2 spaces yields " << (x << 2) << endl;
cout << "Shift bits in x left 1 space yields " << (x >> 1) << endl;

    return 0;
}

These comparisons and shifts result in the following values:

x & y = 4
x | y = 30
x ^ y = 26
Inversion of x is -13
Shift bits in x left 2 spaces yields 48
Shift bits in x left 1 space yields 6

It’s worth noting that the value for shifting bits does not need to be a constant. So for example, x << y is a valid use of the shift left operator.

Operator Overloading

With C++, it’s even possible to have operators work for user-defined classes. In effect, we can use the “+” operator and overload it so that it’s possible to even add two complex objects together. To perform this, we’ll need to rely on the “operator” function. We can overload the operator function with many different operators.

Let’s say we have a class called “Complex.” We’ve used this class to generate three different objects for us: r1, r2 and r3. We can use the operator+ function to add even these three complex objects together.

When we overload “+”:

operator+(argument_list)

We can then add together the complex objects located in “Complex” as if they were simple variables:

r3 = r1 + r2;

This is just one of the many uses of operator overloading. Again, this can be used with most of the operators we’ve covered today.

Become a C++ Developer With Udacity

To master C++, you’ll have to get comfortable with C++ operators. While operators can be easy to learn, we’ve only scratched the surface on what operators can accomplish. Our expert-led C++ Nanodegree will not only guide you through operators, but also equip you with all the skills you’ll need to build your own application using C++. Get started today!?

Start Learning

C++ Classes Explained

C++ likely would not exist without classes. As the original C programming language grew more decipherable, C++ was born. Because C++ was built entirely with objects in mind, C++ uses classes to make it easy to work with objects. Classes and objects became the building blocks C++ uses for creating streamlined and easy-to-read code.

What exactly is a C++ class, and how does it tie into making it easy to use, follow and compile code? We’re glad you asked.



Continue Reading

Working with Box and Text Shadows

The technique of creating Shadows utilizes both HTML (Hypertext Markup Language) and CSS (Cascading Style Sheets). As you know from previous tutorials, HTML is the foundational code that is used to structure a web page and its content while CSS is used to enhance your web page with creative design aspects. 

In this tutorial, we will explore how you can give your web page something extra by applying shadows to boxes as well as to text. For this tutorial, let’s examine what it takes to do a simple layout so that you feel comfortable creating shadows. All you need to start with is a simple code editor such as Notepad which is free.



Continue Reading

HTML Web Design: Anything and Everything You Need to Know

Welcome to the HTML hub! This guide will provide you with an exhaustive list of everything that you need to know about HTML— one of the most vital programming languages for creating and designing web pages today.

You’ll find everything from HTML basics, to creative more advanced HTML techniques in this guide. This is a living document so please come back and visit us as we continue to add more published content.



Continue Reading

澳门葡京网站 Coalesce — Weeding Through The NULLs

Relational databases store information in tables — with columns that are analogous to elements in a data structure and rows that are one instance of that data structure. In 澳门葡京网站, a table cell without a value contains a special marker, NULL, which is not the same as zero, an empty string, or any other kind of value that works with equality tests; i.e. NULL != 0, NULL != "“, etc. The 澳门葡京网站 Coalesce statement is one way of processing these NULL values for common uses like text processing.



Continue Reading

澳门葡京玩法 vs. Data Scientist: What You Need To Know in 2021

Did you know that the global revenue for big data and analytics is expected to reach nearly 275 billion dollars by 2022? For enterprises looking to leverage their data to its highest potential, one of the biggest challenges is finding practical and scalable ways to use the data. To fully unlock the power of that data, you’ll likely need a data analyst or a data scientist on your team.

The real question then is: do you need a data analyst or a data scientist? Let’s take a look at the role of data analyst vs. data scientist to figure out what’s right for your enterprise.



Continue Reading

What are Javascript Objects? Containers for Reusable Properties and Behaviors

Javascript is a versatile programming language; you can create short scripts of only a few lines or complex modules that contain many. Developers handling many web pages often need to reuse their Javascript code; copying and pasting scripts between pages is a tedious and error-prone process.

The Javascript standard provides the ability to create reusable code in the form of Javascript objects. Javascript objects provide complex functionality with minimal code, making new scripts easy to maintain and fast to load.

Continue Reading