Limit with powers in C++

closed account (9G6fSL3A)
Ive been playing around with some code. When running the first code, i get an answers, but when running the second lot I get 0. The only diffrence is that I change the power from 29 to 30. Could someone help explain this or a way around it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
   int pow2(int n){
  int result=1;
  for (int i=0;i<n;i++){
    result*=2;
  }
  return result;
}

#include <iostream>

int main()
{
    std::cout << pow2(29) << '\n' ;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
 int pow2(int n){
  int result=1;
  for (int i=0;i<n;i++){
    result*=2;
  }
  return result;
}

#include <iostream>

int main()
{
    std::cout << pow2(30) << '\n' ;
}
I don't know what could be the problem. What OS and compiler are you using?

[edit] I can guess about the problem, but without knowing more it is just a couple of guesses...
Last edited on
closed account (9G6fSL3A)
windows 8
DEV C++ 5.4.2
Running you code:

For 29 i get 536870912.
For 30 i get 1073741824.

Which is in agreement with my calculator :)

Run on VS2010, windows 8.
1
2
3
4
5
6
7
8
int main()
{
  for ( int i=28; i<33; ++i )
    {
      std::cout << i << "  " << pow2(i) << '\n' ;
    }
  return 0;
}
28  268435456
29  536870912
30  1073741824
31  -2147483648
32  0

# file pow2
pow2: ELF 64-bit LSB executable, x86-64, version 1 (SYSV),
  dynamically linked (uses shared libs), for GNU/Linux 2.6.18

# g++ --version
g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)


DEV C++ 5.4.2 is not a compiler. What is the version of the compiler that it does use?
Last edited on
I doubt it is a simple integer size problem. If he can calculate a 30-bit answer he ought to be able to calculate a 31-bit answer.

Dev-C++ comes with an old g++.

If you know how to generate the assembly code for your program, do that and show us what it is doing.

  g++ -S foo.cpp

Now look at the file "foo.s" and see if you can find a section that starts with something like "__Z4pow2i:" and ends with "_main:".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
__Z4pow2i:
LFB0:
        .cfi_startproc
        pushl   %ebp
        .cfi_def_cfa_offset 8
        .cfi_offset 5, -8
        movl    %esp, %ebp
        .cfi_def_cfa_register 5
        subl    $16, %esp
        movl    $1, -4(%ebp)
        movl    $0, -8(%ebp)
        jmp     L2
L3:
        sall    -4(%ebp)    ; shift left (same as: multiply by 2)
        incl    -8(%ebp)    ; 
L2:
        movl    -8(%ebp), %eax
        cmpl    8(%ebp), %eax
        setl    %al
        testb   %al, %al
        jne     L3
        movl    -4(%ebp), %eax
        leave
        .cfi_restore 5
        .cfi_def_cfa 4, 4
        ret
        .cfi_endproc

As you can see, my GCC optimized those multiplications into simple bitshifts.
Topic archived. No new replies allowed.