Jump to content

Recommended Posts

Posted

I have a general programming question: Where is it best to place variable declarations with regards to control structures?

Sometimes I'll only need a variable inside of an IF statement and I declare it inside, like this...

Func DistListItemGet($vDistList)
  If Not IsObj($vDistList) Then
    ; Find it
    Local $aItems = _OL_ItemFind(...)
    If @error Then Return SetError(1, @error, False)
    
    $vDistList = $aItems[1][1]
    ; Get the object
    $vDistList = _OL_ItemGet(...)
  EndIf
  
  ; Do stuff with the object here
  
EndFunc

I only use $aItems (the result of _OL_ItemFind) inside the If statement, and I won't need it later... is it acceptable programming practice to declare the variable on the inside in this case, or should all variables be declared outside of structures? I realize that declaring variables inside of loops is bad practice, but what about inside of conditionals?

All my code provided is Public Domain... but it may not work. ;) Use it, change it, break it, whatever you want.

Spoiler

My Humble Contributions:
Personal Function Documentation - A personal HelpFile for your functions
Acro.au3 UDF - Automating Acrobat Pro
ToDo Finder - Find #ToDo: lines in your scripts
UI-SimpleWrappers UDF - Use UI Automation more Simply-er
KeePass UDF - Automate KeePass, a password manager
InputBoxes - Simple Input boxes for various variable types

Posted

For the moment you may not need the variable outside the if.  But in the future it might change.  And you will be face with an undeclared variable elsewhere if the condition is not True.  Making debug a bit more tedious in large programs.  I personally prefer playing it safe as it has no impact on size and speed of the script. So I always declare my vars outside a block of statement.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...