TOPIC: Constants, Manipulators and Operator Precedence in C++
Constants
C++ Program - Constants
Code written in Visual Studio Code
// Program to illustrate Constants in C++
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
// CONSTANTS IN C++
const int a = 3;
int a = 444; // I will get an error because a is a constant
cout << "The value of a is: " << a << endl;
// This is the correct option
// const int b = 82;
// cout << "b = " << b;
getch();
return 0;
}
In function 'int main()':
error: conflicting declaration 'int a'
int a = 444; // I will get an error because a is a constant
^
note: previous declaration as 'const int a'
const int a = 3;
^
Manipulators
C++ Program - Manipulators
Code written in Visual Studio Code
// Program to illustrate Manipulators in C++
#include<iostream>
#include<conio.h>
#include<iomanip>
using namespace std;
int main()
{
int a = 77, b = 777, c = 7777;
cout << "The value of a without setw is: " << a << endl;
cout << "The value of b without setw is: " << b << endl;
cout << "The value of c without setw is: " << c << endl;
cout << "The value of a is: " << setw(4) << a << endl;
cout << "The value of b is: " << setw(4) << b << endl;
cout << "The value of c is: " << setw(4) << c << endl;
getch();
return 0;
}
The value of a without setw is: 77
The value of b without setw is: 777
The value of c without setw is: 7777
The value of a is: 77
The value of b is: 777
The value of c is: 7777
In the above output, the value is formatted to the right when we use setw()
Operator Precedence in C++
Operators | Precedence |
---|---|
++ (post increment), -- (post decrement) | Highest |
++ (pre-increment), --
(pre-decrement), sizeof, ! (not), - (unary minus), + (unary plus) |
↓ |
* (multiply), / (divide), % (modulus) | ↓ |
+ (add), - (subtract) | ↓ |
< (less than), <=(less than or equal), > (greater than), >= (greater than or equal) |
↓ |
== (equal), != (not equal) | ↓ |
&& (logical AND) | ↓ |
|| (logical OR) | ↓ |
?: (conditional expression) | ↓ |
= (simple assignment operator) | ↓ |
comma operator | lowest |
In the above table, we can see that the operators are given from Highest to lowest precedence of operators.
C++ Program - Precedence of Operators
Code written in Visual Studio Code
// Program to illustrate Precedence of Operators in C++
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int a = 444, b = 454;
int c = (a * 100) + b;
int d = ((((a * 100) + b) - 44) + 10);
cout << c << endl;
cout << d;
getch();
return 0;
}
44854
44820
You can write more code examples for checking precedence for yourselves. You can also check more about C++ operator precedence on website cppreference.com
More blog posts coming soon!
Coding is the art of turning imagination into innovation.
- Unknown