Search code examples
c++stdunsignedsigned

signed or unsigned int in c++


How can i check if given int(or any other data type) is signed or unsigned? I found this function while searching,

std::numeric_limits<int>::is_signed

But i can only input the data type, is there a way that i can check by variable name, like.

signed int x = 5;

Now i want to make a function which checks that x is a signed int or not.

And if you guys can answer these little questions, that would be highly appreciated.

  1. Why do we use '::' these operators after std?
  2. What do they mean when we use them in std::cout, is it the same?
  3. Here numeric_limits<> is a class or what?
  4. And again, why are we using these '::' before is_signed?

Solution

  • is there a way that i can check by variable name

    Since C++11, we have decltype to get the type of a variable or expression:

    std::numeric_limits<decltype(x)>::is_signed
    

    Historically, it was trickier; the only way to infer a type from a variable was through template argument deduction:

    template <typename T>
    bool is_signed(T const &) {
        return std::numeric_limits<T>::is_signed;
    }
    

    Why do we use '::' these operators after std?

    That's the scope resolution operator, saying that we want the name numeric_limits to be looked up in the namespace std.

    What do they mean when we use them in std::cout, is it the same?

    Yes. Like most names in the standard library, cout is also scoped inside namespace std.

    Here numeric_limits<> is a class or what?

    It's a class template, containing various static variables and functions that describe the type used as the template argument. Here's a reference: http://en.cppreference.com/w/cpp/types/numeric_limits

    And again, why are we using these '::' before is_signed?

    Again, that resolves the scope by saying we want the name is_signed to be looked up inside the class scope of std::numeric_limits<int>.