0

unsigned long long mem_size = 1024 * 1024 * 1024 *1024;

Why in vs2013, I find the variable mem_size is not 240 but 0?

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56
Johnson
  • 1
  • 1
  • Are you using 64bit os? – SpongeBob Nov 01 '20 at 08:20
  • The variable is unsigned so if you reach the limit, it goes on overflow and returns to the minimum value 0. – Sintuz Nov 01 '20 at 08:20
  • 7
    `1024` has type `int` and won't be promoted to `long long` automatically. Use `1024ULL`. – Evg Nov 01 '20 at 08:21
  • @Evg Please turn that into an answer. It seems even already sufficiently explained. – Yunnosch Nov 01 '20 at 08:22
  • @Sintuz `1024*1024*1024*1024` is `2^40` can be represented with 64 bits. No going over the top there. Even if it overflows and wraps around it shouldn't be 0. – Tony Tannous Nov 01 '20 at 08:23
  • @Yunnosch, there should be a perfect dupe for this question. I'm looking for it now. – Evg Nov 01 '20 at 08:23
  • 1
    @Evg worth mentioning then int overflow is undefined behavior, any value could be expected than 0 as well? – Tony Tannous Nov 01 '20 at 08:24
  • @Evg Fine with me. Either name it or provoke another user in providing it by making an answer. Please. I want this out of the list of unanswered questions. – Yunnosch Nov 01 '20 at 08:24
  • 2
    @Yunnosch, perfect dupe has been found. :) – Evg Nov 01 '20 at 08:26
  • 2
    @Evg I wish voting the quality of a found dupe were possible.... There are so many examples of abused hammers now. And of course I do not mean this one. – Yunnosch Nov 01 '20 at 08:27
  • This is my first question in stack overflow. Thanks all , especially @Evg。Your answer is ok for me。@Evg – Johnson Nov 01 '20 at 08:33
  • What you do with the result of an expression does not affect how the expression is evaluated. Your expectation that assigning it to a `long long` would cause the computation be done as a `long long` is not met. – David Schwartz Nov 01 '20 at 08:36
  • So I should hide this question ,right ? @Evg – Johnson Nov 01 '20 at 08:51
  • @Johnson, please don't do it. It's a useful question. Question with a dupe ≠ bad question that should be deleted. – Evg Nov 01 '20 at 08:55
  • 1
    @SpongeBob `int` is 32-bit in both 32 and 64-bit platforms, so the result is the same: the expression overflows – phuclv Nov 01 '20 at 10:42

0 Answers0