digitalmars.D.learn - Why do I get stack overflow?
- Ary Borenszweig (13/13) May 24 2009 When I compile this code I get "stack overflow" printed in the console.
- Moritz Warning (3/18) May 24 2009 Because you generate fact!(-1)(), fact!(-2)() and so on at compile time.
- Ary Borenszweig (3/23) May 24 2009 Thanks. Later in my head I instantiated the template and noticed the
- bearophile (5/7) May 25 2009 In time I have created similar problems in my code 2-3 times, missing a ...
- Christopher Wright (2/17) May 24 2009 Like Moritz said. You need to use "static if" there rather than "if".
When I compile this code I get "stack overflow" printed in the console. Anyone know why? --- int fact(int X)() { if(X == 0) { return 1; } else { int temp = fact!(X - 1)(); return X * temp; } } const someVar = fact!(0)(); ---
May 24 2009
On Sun, 24 May 2009 20:49:53 -0300, Ary Borenszweig wrote:When I compile this code I get "stack overflow" printed in the console. Anyone know why? --- int fact(int X)() { if(X == 0) { return 1; } else { int temp = fact!(X - 1)(); return X * temp; } } const someVar = fact!(0)(); ---Because you generate fact!(-1)(), fact!(-2)() and so on at compile time. You recursive template doesn't terminate.
May 24 2009
Moritz Warning escribió:On Sun, 24 May 2009 20:49:53 -0300, Ary Borenszweig wrote:Thanks. Later in my head I instantiated the template and noticed the problem.When I compile this code I get "stack overflow" printed in the console. Anyone know why? --- int fact(int X)() { if(X == 0) { return 1; } else { int temp = fact!(X - 1)(); return X * temp; } } const someVar = fact!(0)(); ---Because you generate fact!(-1)(), fact!(-2)() and so on at compile time. You recursive template doesn't terminate.
May 24 2009
Ary Borenszweig:Thanks. Later in my head I instantiated the template and noticed the problem.In time I have created similar problems in my code 2-3 times, missing a "static" before some "if". Can't the compiler help spot such bugs? If the variables a dynamic if works on are constants (expecially if they are types) the compiler may give a warning... Bye, bearophile
May 25 2009
Ary Borenszweig wrote:When I compile this code I get "stack overflow" printed in the console. Anyone know why? --- int fact(int X)() { if(X == 0) { return 1; } else { int temp = fact!(X - 1)(); return X * temp; } } const someVar = fact!(0)(); ---Like Moritz said. You need to use "static if" there rather than "if".
May 24 2009