Search code examples
c++variablesnegative-integer

How to make negative of a variable? C++


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?


Solution

  • 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;