How to write a short literal in C++?

C++ProgrammingServer Side Programming

Here we will see how will be the short literal in C++. In C or C++, different types of data have different literals. These are listed below.

Sr.NoDatatypes & Literals
1int
5
2unsigned int
5U
3Long
5L
4long long
5LL
5float
5.0f
6double
5.0
7char
‘\5’

Now, there are int, long float, double etc, but no short is present. So we cannot use any literals for short type data. But we can solve this problem by explicit typecasting.

If we use the line like below, then it will be converted into short.

int x;
x = (short) 5; //converted into short type data.

Example

#include <iostream>
using namespace std;
main() {
   int x;
   x = 65700;
   cout << "x is (as integer):" << x << endl;
   x = (short)65700; //will be rounded after 2-bytes
   cout << "x is (as short):" << x << endl;
}

Output

x is (as integer):65700
x is (as short):164
raja
Published on 26-Apr-2019 11:46:55
Advertisements