Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 996
user3834119 Avatar asked May 30 '26 00:05

user3834119


2 Answers

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>.

like image 147
Mike Seymour Avatar answered May 31 '26 14:05

Mike Seymour


Like this:

constexpr bool is_signed = std::numeric_limits<decltype(x)>::is_signed();

This will fail to compile if there's no specialization of numeric_limits for the type of x, though. A more generic solution would be is_signed from <type_traits> header:

constexpr bool is_signed = std::is_signed<decltype(x)>::value;

And yes, both are numeric_limits and is_signed are class templates.

like image 43
jrok Avatar answered May 31 '26 13:05

jrok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!