Check if a variable exists
Kirk McDonald
kirklin.mcdonald at gmail.com
Fri Aug 18 12:39:37 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?
>
Oh. Then you don't want this at all. Use the bool. :-) The reason is
simple: if you declare the temporary before the for loop, then it will
always exist after the for loop. If you declare the temporary inside the
for loop, then it only has the scope of the for loop; it will cease to
exist when the loop ends. Whichever way you do it, whether it exists or
not after the for loop never varies.
Example 1: Declare before the loop
int temp;
for (;;) {
// stuff
}
// temp exists here
Example 2: Declare inside the loop
for (;;) {
int temp;
// stuff
}
// temp doesn't exist anymore; its scope ended
>
>>The answer, though, is this:
>>
>>static if (is(typeof(my_variable))) {
>> // ...
>>}
>
>
> Thanks. What is the static keyword for?
> Peter
http://www.digitalmars.com/d/version.html#staticif
Static if is analogous to #if/#endif in the C preprocessor. It does not
apply here, so nevermind what I told you. :-)
--
Kirk McDonald
Pyd: Wrapping Python with D
http://pyd.dsource.org
More information about the Digitalmars-d-learn
mailing list