Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Simple Operators | Introduction to Operators
C++ Introduction
course content

Course Content

C++ Introduction

C++ Introduction

1. Getting Started
2. Variables and Data Types
3. Introduction to Operators
4. Introduction to Program Flow
5. Introduction to Functions

Simple Operators

The assignment operator (=) is used in programming to assign a value to a variable. The syntax looks as follows:

cpp

main

1234567891011
#include<iostream> int main() { int myVar = 9; int yourVar; yourVar = myVar; //assign yourVar the value of myVar std::cout << myVar << std::endl << yourVar; }

It works exactly the same with the string data type:

cpp

main

12345678910111213
#include <iostream> #include <string> int main() { std::string myVar = "codefinity"; std::string yourVar; yourVar = myVar; //assign yourVar the value of myVar std::cout << myVar << std::endl; std::cout << yourVar << std::endl; }

The equality (==) and inequality (!=) operators are used to numerically compare 2 variables:

cpp

main

1234567891011
#include <iostream> int main() { int var = 9; int yourVar = (var == 9); int myVar = (var == -9); std::cout << yourVar << std::endl; std::cout << myVar << std::endl; }

Why 1 and 0? This is an alternative approach for utilizing the boolean data type. When the expression var == 9 is true, it is represented as 1, and it means that var is indeed equal to the number 9. Conversely, when the expression var == -9 is false, it is represented as 0, indicating that var is not equal to the number -9.

The inequality (!=) operator is doing exactly the opposite:

cpp

main

123456789101112131415
#include<iostream> int main() { int var = 9; //if var is equal 9, then 0 (false) int yourVar = (var != 9); //if var is not equal -9, then 1 (true) int myVar = (var != -9); std::cout << yourVar << std::endl; std::cout << myVar << std::endl; }

Everything was clear?

Section 3. Chapter 1
We're sorry to hear that something went wrong. What happened?
some-alt