Check if a variable exists

nobody nobody at mailinator.com
Sun Aug 20 01:55:29 PDT 2006


Peter Thomassen wrote:
> Kirk McDonald schrieb am Freitag, 18. August 2006 21:14:
>>> Is it possible to check if a variable exists, like PHP's isset()?
>> Typically, you only ever have to ask when doing fairly complex template
>> stuff; this is largely the point of a statically-typed language. Mind if
>> I ask why you need to check for this?
> 
> I've got a for loop which contains an if statement checks something
> depending on the counting loop var i. If true, some action producing a
> temporary variable is taken.
> 
> After the for loop, I want to do further things if and only if the "if" tree
> has been entered at least once. I cannot check that using i because that
> has modified during the loop. Of course I could declare a bool in the "if"
> tree and check for that, but I know that I will have the temporary variable
> set, if the "if" tree has been entered. So, why not check for this?

It is strictly not possible to introduce a variable into one scope from a scope 
which it encloses. This means any vars you define inside a function will not be 
available outside. Also loops have their own scope and so any variable you 
declare inside the loop is gone once the loop completes. The way to do what you 
want is by declaring a bool var /before/ the loop and then using that var inside 
the loop. Here is an example that demonstrates how to do what you want:

   bool isPrime(ubyte n)
   {
     bool prime = true;
     for(uint i = 2; i < ubyte.max; i+=1)
     {
       if( n != i )
       {
         if( (n%i) == 0 )
           prime = false;
       }
     }
     // i now out of scope and undefined
     return prime;
   }

   int main(char[][] args)
   {
     for(ubyte n = 2; n < ubyte.max; n+=1)
     {
       if( isPrime(n) )
         dout.writeLine(toString(n)~" is prime.");
       else
         dout.writeLine(toString(n)~" is not prime.");
     }
     return 0;
   }

> 
>> The answer, though, is this: 
>>
>> static if (is(typeof(my_variable))) {
>>      // ...
>> }
> 
> Thanks. What is the static keyword for?
> Peter

The reason people slipped away without answering this question is that static is 
very much like smurf. It can mean so many things:

   class Example
   {

     static int func()
     {
       static if(a)
         static int b;
       else static if(z)
       {
         static float y;
         int b = cast(int) y;
       }
       return ++b;
     }
   }



The conditional compilation section of the D lang spec explains 'static if.'

Conditional Compilation
http://digitalmars.com/d/version.html

A StaticIfConditional condition differs from an IfStatement in the following ways:

...
4. It must be evaluatable at compile time.


That means since you will only know when the program is running whether an if 
statement succeeded  static if is of no use.



More information about the Digitalmars-d-learn mailing list