www.digitalmars.com         C & C++   DMDScript  

D.gnu - Local variabled and nested functions

reply Fredrik Olsson <peylow gmail.com> writes:
This small test-case:

import std.stdio;

int foo(int a) {
   int bar(int b) {
     a += b;
     if (b > 0) {
       return bar(b - 1);
     } else {
       return a;
     }
   }
   return bar(a);
}

int main(char[][] args) {
   writefln("a=", foo(3));
   return 0;
}

Correctly gives "a=9" on gdc 0.15. But "a=72592" on gdc 0.16.

Same goes for the smaller example (with purely local variable):
int bar() {
   int a = 1;
   int baz(bool onemore) {
     if (onemore)
       return baz(false);
     else
       return a;
   }
   return baz(true);
}

Should always give 1, but mostly gives 72504 for me. I guess the pointer 
to the parents locals get screwed up. It works as long as I do not use 
recursion.

regards
	Fredrik Olsson
Nov 29 2005
parent Thomas Kuehne <thomas-dloop kuehne.cn> writes:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Fredrik Olsson schrieb am 2005-11-30:
 This small test-case:

 import std.stdio;

 int foo(int a) {
    int bar(int b) {
      a += b;
      if (b > 0) {
        return bar(b - 1);
      } else {
        return a;
      }
    }
    return bar(a);
 }

 int main(char[][] args) {
    writefln("a=", foo(3));
    return 0;
 }

 Correctly gives "a=9" on gdc 0.15. But "a=72592" on gdc 0.16.

 Same goes for the smaller example (with purely local variable):
 int bar() {
    int a = 1;
    int baz(bool onemore) {
      if (onemore)
        return baz(false);
      else
        return a;
    }
    return baz(true);
 }

 Should always give 1, but mostly gives 72504 for me. I guess the pointer 
 to the parents locals get screwed up. It works as long as I do not use 
 recursion.

 regards
 	Fredrik Olsson

Added to DStress as http://dstress.kuehne.cn/run/n/nested_function_07_A.d http://dstress.kuehne.cn/run/n/nested_function_07_B.d http://dstress.kuehne.cn/run/n/nested_function_07_C.d Thomas -----BEGIN PGP SIGNATURE----- iD8DBQFDlAHG3w+/yD4P9tIRAmj1AKC8p+lGpZxTIPLzOaGAqCskTX5eYwCguINl pYmZyBhGryz2XrYSfM0JWUs= =+uKA -----END PGP SIGNATURE-----
Dec 04 2005