- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
- C++ Advanced
- C++ Files and Streams
- C++ Exception Handling
- C++ Dynamic Memory
- C++ Namespaces
- C++ Templates
- C++ Preprocessor
- C++ Signal Handling
- C++ Multithreading
- C++ Web Programming
Operators Precedence in C++
Try the following example to understand operators precedence concept available in C++. Copy and paste the following C++ program in test.cpp file and compile and run this program.
Check the simple difference with and without parenthesis. This will produce different results because (), /, * and + have different precedence. Higher precedence operators will be evaluated first −
#include <iostream> using namespace std; main() { int a = 20; int b = 10; int c = 15; int d = 5; int e; e = (a + b) * c / d; // ( 30 * 15 ) / 5 cout << "Value of (a + b) * c / d is :" << e << endl ; e = ((a + b) * c) / d; // (30 * 15 ) / 5 cout << "Value of ((a + b) * c) / d is :" << e << endl ; e = (a + b) * (c / d); // (30) * (15/5) cout << "Value of (a + b) * (c / d) is :" << e << endl ; e = a + (b * c) / d; // 20 + (150/5) cout << "Value of a + (b * c) / d is :" << e << endl ; return 0; }
When the above code is compiled and executed, it produces the following result −
Value of (a + b) * c / d is :90 Value of ((a + b) * c) / d is :90 Value of (a + b) * (c / d) is :90 Value of a + (b * c) / d is :50
cpp_operators.htm
Advertisements