-3

I apologize if this error is the result of a typo, but I can't figure out how to make my variable negative when the correct syntax should be y=-x;

std::cout << "loop size = " << loop_size_ << std::endl;
core::Size neg_loop_size_ = -loop_size_;
std::cout << "neg loop size = " << neg_loop_size_ << std::endl;

When I run it, this is the result I get:

loop size = 4
neg loop size = 18446744073709551612

How do I get a new variable equal to -4?

Amanda
  • 202
  • 1
  • 3
  • 8
  • 5
    It's an unsigned integral type that's why you are not getting negative value. The data type of core::Size should be signed to hold native integer – Asesh Oct 06 '17 at 05:14
  • 2
    It seems that `core::Size` is an *unsigned* integer type, which means it can never be "negative". What happens if you attempt to *print* `-loop_size_`? – Some programmer dude Oct 06 '17 at 05:15
  • That makes sense that it's unsigned - core::Size is an integer, intended for something that never goes negative. I will use a different data type... Thanks! – Amanda Oct 06 '17 at 05:16

2 Answers2

1

This is undoubtedly a signedness issue. You have specified that neg_loop_size is core::Size. core::Size is likely meant to be a length-style measurement. A length cannot be negative. ("How many kilometers did you run today, Josy?", "Why, I ran negative 4 kilometers!")

So, the compiler and cout are correctly coercing -1 to "loop around" to the highest number possible with 8 bytes. Consider:

   18446744073709551612 + 4 - 1
 = 2^65 -1
 = 0xFFFFFFFFFFFFFFFF
 = (core::Size) 0 - 1

If you want a negative value, you will either need to do some string manipulation and conversion yourself, or choose a datatype that the compiler and cout will interpret as negative. For example:

int i = 0;
i -= 1;
std::cout << "i = " << i << std::endl;
hunteke
  • 3,648
  • 1
  • 7
  • 17
0

I think the issue is Core:Size data type is unsigned. So you are having issue.

If you store the value in a integer you should get the required output.

  int main() {
      int i = 5;
      int j = -i;
      cout<<endl<< j << endl;

     return 1;
}

Output ---

$>:~/tmp$ vim c.cpp
$>:~/tmp$ g++ c.cpp
$>:~/tmp$ ./a.out
-5
$
Seshadri VS
  • 550
  • 1
  • 6
  • 24