Why does conversion of a negated `size_t` value to `double` fail?

3 weeks ago 14
ARTICLE AD BOX

In this line:

double my_double_value = -my_size_t_value*cash;

According to operator precedence first -my_size_t_value is calculated, and according to the C++ rules done in "unsigned mode" because size_t is unsigned.
So an expression that negates a small size_t will produce a large positive value - for example: negating a size_t with value 2 produces the value std::numeric_limits<size_t>::max()-1 which, for a 32-bit size_t, is 4294967294 and for 64-bit size_t is 18446744073709551614
(the latter matches your case according to the final output of 1.84467e+22).

Only then the result is converted to double for multiplying by cash.

So it is equivalent to:

double my_double_value = (-my_size_t_value)*cash;

If you change it to:

double my_double_value = -(my_size_t_value*cash);

You will get the expected result because now first the multiplication will be done, and for that my_size_t_value will be converted to double.

See live demo.

Using int (which is signed) instead of size_t (unsigned) gives you the expected result because now the unary negation does what you expect.

wohlstad's user avatar

6 Comments

2025-11-26T08:38:35.907Z+00:00

Nice! (although it doesn't explain why -my_size_t_value - before the static_cast<double> - results in a value which might not be intuitive).

2025-11-26T10:07:22.673Z+00:00

2s complement describes a representation of signed integers, not unsigned ones.

2025-11-26T11:48:34.09Z+00:00

I meant that a value that would have been a small negatives value (in 2s complement) will denote a high positive one as an unsigned. Editted to rephrase, but fill free to edit if you can phrase it better.

2025-11-26T11:55:03.613Z+00:00

OK; an edit suggested. I decided it was worth being specific on what is happening for the OP. Feel free to tweak.

2025-11-26T12:19:58.907Z+00:00

@Peter I modified your edit to add info for 64-bit system, which seem to be the case for the OP (according to the printed value of 1.84467e+22).

2025-11-26T12:29:22.327Z+00:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article