1

In the following code:

#include <armadillo>

using namespace arma;

int main()
{
    mat A;
    auto x=A.n_rows-5;
    ....

x is long long unsigned int and I want it to be long long int. How can I fix this problem?

It should be noticed that on different versions of this library, different types have been used, so I cannot mention long long int directly and I need to use auto.

1
  • The short answer is to convert A.n_rows to be long long int before doing the subtraction. Bear in mind that the behaviour will be undefined if A.n_rows is a value that cannot be represented in a long long int (there are values a long long unsigned can represent that a long long int cannot), so you will need to deal with that. You also haven't explained why you want x to be signed.
    – Peter
    Oct 10, 2015 at 4:43

3 Answers 3

5

Since you are already using armadillo, I think the best (or easiest) way would be using arma::sword.

sword x = A.n_rows - 5; // This can also compile without C++11.

It will solve the problem of "different versions of this library, different types have been used", since A.n_rows has the type arma::uword, which is unsigned version of arma::sword. See, http://arma.sourceforge.net/docs.html#uword

1
  • using a more explicit declaration might make the intent clearer: auto x = sword(A.n_rows) - 5;
    – hbrerkere
    Oct 13, 2015 at 4:51
1

You can use the C++11 type traits library to get a signed or unsigned version of a numeric type.

To get an unsigned int:

std::make_unsigned<int>::type

So to get a signed version of A.n_rows, try:

std::make_signed<decltype(A.n_rows)>::type x = A.n_rows - 5;

For any other qualifiers, there are corresponding templates to convert between types:

0

Change

auto x=A.n_rows-5;

To

long long int x = (long long int)(A.n_rows - 5);

In order to cast away the unsigned.

3
  • You can keep auto when you cast: auto x = (long long int)(A.n_rows - 5); Oct 10, 2015 at 3:22
  • 2
    That conversion will give undefined behaviour if A.n_rows - 5 results in a value that a long long int cannot represent.
    – Peter
    Oct 10, 2015 at 4:45
  • Are you joking? did you read my post about why I do need to use auto?
    – barej
    Oct 10, 2015 at 22:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.