Why overflow occurs.
#include <cstddef> #include <iostream> int main() { std::size_t max = 1000000 * 1000 * 4; } Warning C4307 *: integer constant overflow
Why overflow occurs.
#include <cstddef> #include <iostream> int main() { std::size_t max = 1000000 * 1000 * 4; } Warning C4307 *: integer constant overflow
Constants (containing a number) are interpreted as 32-bit signed integer by default (your value is missing one bit of 31-bit + 1 bit sign), but your type is 32-bit unsigned (size_t), so you need to specify "suffix" - literal type in this case U . Numeric constants are called literals (integer literals or integer literals).
std::size_t max = 1000000U * 1000* 4; The type of "literal" is determined by the first literal, the other participants in the operation - the compiler converts according to the type of the first, so the next two U can be omitted.
Whole literals are short: U - unsigned, L long (32-bit), UL = unsigned 32-bit, LL 64-bit signed (C ++ 11 standard), ULL 64-bit unsigned (too). (The length of U same as the length of unsigned int , which in some compilers may have a length other than 32.)
For more information https://en.cppreference.com/w/cpp/language/integer_literal
If the compiler swears at 1000000LL - then your compiler does not support this type of literal - you will have to write the number completely. If you still need to "merge the code" - you can use #define (usually try to avoid such structures, but in this case I think that you can apply). Like so
#define triple_const(a,b,c) a##b##c std::size_t max = triple_const(4,000000,000) There are also other types of literals (string, boolean, floating-point numbers, and n p).
1000000 * 1000 * 4 == 4 000 000 000 , but that is if unsigned int . In this case, int(1000000) * int(1000) * int(4) is the int overflow and is equal to -294967296 . Further the negative number is assigned to the unsigned type - it turns out nonsense
(unsigned)-294967296 - well, what is your result? It does not work nonsense. - nick_n_a(uint32_t)-294967296 will be just 4 000 000 000 - probably you will be surprised - this is just 32 bits. For constants there is a suffix. - nick_n_a(unsigned)-294967296 ? I did not write this. - ffkYou are trying to calculate the value of the expression 1000000 * 1000 * 4 . All operands of this expression are of type int and the entire expression is evaluated within an int domain. But this expression on your platform cannot be calculated within the domain of type int - an overflow occurs. This is what the compiler tells you.
Source: https://ru.stackoverflow.com/questions/838956/
All Articles
inttype. And this is the overflow. - AnT