Zik
Zik

Reputation: 1576

What is the difference between these data types?

In C++, what is the difference between short int, unsigned int, signed int, and int? What are there applications? When do you use short int, unsigned int, etc. ?

Upvotes: 0

Views: 874

Answers (3)

Trevor Hickey
Trevor Hickey

Reputation: 37914

Take a look! You tell me!

#include <iostream>
#include <cstdlib>
#include <limits>
using namespace std;

int main(){

    cout << "min_int = " << numeric_limits<int>::min() << endl;
    cout << "max_int = " << numeric_limits<int>::max() << endl;

    cout << "min_unsigned_int = " << numeric_limits<unsigned int>::min() << endl;
    cout << "max_unsigned_int = " << numeric_limits<unsigned int>::max() << endl;

    cout << "min_short = " << numeric_limits<short>::min() << endl;
    cout << "max_short = " << numeric_limits<short>::max() << endl;

    cout << "min_unsigned_short = " << numeric_limits<unsigned short>::min() << endl;
    cout << "max_unsigned_short = " << numeric_limits<unsigned short>::max() << endl;

    return EXIT_SUCCESS;
}

Upvotes: 4

geniusburger
geniusburger

Reputation: 428

If you want to create a function that accepts only positive numbers, which might be done to restrict others from passing it negative values or from freeing your function from having to check the sign of the values passed, you could use an unsigned int. Of course this doesn't stop anybody from casting a negative int to an unsigned int. This will just results in your function interpreting it as a huge number (since the most significant bit will be 1 to represent the previously negative number) but then that's the fault of the person casting that value.

Upvotes: 1

dlundquist
dlundquist

Reputation: 889

In most cases int is what you want, if you are going to be strictly working with non negative numbers unsigned is good. But often standard library function return negative values for errors.

Short is primarily used for small values in larger data structures as a memory optimization, or for interfacing with network or file formats.

Upvotes: 1

Related Questions