const, final, scope function parameters
Regan Heath
regan at netmail.co.nz
Sun May 27 13:36:56 PDT 2007
Myron Alexander Wrote:
> janderson wrote:
> > Walter Bright wrote:
> >> 2) Having to turn off one of the const, final, or scope, introduces
> >> the need for some sort of "not" keyword, like mutable, !const, !final,
> >> etc. It comes off looking bizarre.
> >
> > On this point, couldn't it be something like, if you define const, final
> > or scope then the default "const final scope" is removed?
> >
> > [snip]
>
> I agree with this suggestion. I always insist on the most restrictions
> possible and relaxing restrictions on a case-by-case basis. This is what
> I call tight code :)
>
> I understand scope within the function body but I do not understand
> scope for parameters. How does scope affect class references, arrays,
> and primitives (like int)?
It's my understanding that if you have:
Class A { int a; }
void foo(A aa, char[] bb, int cc) {}
void main()
{
A a = new A();
char[] b = "b";
int c = 1;
foo(a,b,c);
}
when you call 'foo' you get a copy of a, b, and c called aa, bb, and cc. These copies are naturally 'scope' because they only exist in the function scope, after which they vanish; because they are copies on the stack.
Therefore having a foo like this would be illegal:
//variables in a higher scope
A* pa;
char[]* pb;
int *pc;
void foo(A aa, char[] bb, int cc)
{
pa = &aa;
pb = &bb;
pc = &cc;
}
you would be violating 'scope' and should get errors. Likewise returning the address of one of these would be illegal:
A* foo(A aa) { return &aa; }
Because classes and arrays are reference types and int is a value type I believe this code is legal and does not violate scope.
//variables in a higher scope
A* aaa;
char[]* bbb;
int *ccc;
void foo(A aa, char[] bb, int cc)
{
aaa = aa;
bbb = bb;
ccc = cc;
}
I think I may have muddied the waters with bad examples prior to this point.
Regan Heath
More information about the Digitalmars-d
mailing list