Why Declare Variables ?

Navigation:  Appendices > Macro Language > Variables > Declaring Variables >

Why Declare Variables ?

Previous pageReturn to chapter overviewNext page

Most beginning users of typed languages, such as the Q++ Macro Language, find the requirement of declaring variables a waste of time; surely the compiler is smart enough to know what variable I am using ?

 

Not so. Declaring variables helps the Macro compiler to verify your code and warn you if :

 

You are using variables of the wrong type.

 

You are using variables that you have not declared.

 

You can easily understand that trying to stuff the value 'Michael Jackson' into a function that expects a number will cause problems, and therefore that the compiler needs to check that round pegs are not going into square holes. However, you might feel that the second point is moot, since you do not care to be warned if you are using a variable which you have not declared. Right ?

 

Wrong. Suppose the compiler did not check that every variable you use was previously declared. It could easily just add any new variable it encounters to the list of variables it keeps in memory. Consider then the following example code :

 

 nDayOfLastSundayBeforeChristmas = DayOf(nSomeDate)

 bIsThe23rd = EqualN(nDateOfLastSundayBeforeChristmas ,23)

 

The above looks like it calculates the day (1-31) on which the Sunday before Christmas falls, and then checks if that is equal to 23.

 

Unfortunately the first line sets the value to nDay... while the second line compares 23 to nDate... Since you did not declare variables, when the compiler encountered nDate... it assumed that it was a new integer variable, initialized it to 0 and then compared it to 23. Not surprisingly, bIsThe23rd turns out to be always false and you cannot figure out why.

 

Don't think of declaring variables as a chore you do to help the compiler. Think of it as you telling the compiler these and only these are the variables I will allow. I want you to warn us if any other variable occurs.


Topic 134000 updated on 01-Oct-2001.
Topic URL: http://www.qppstudio.net/webhelp/index.html?whydeclarevariables.htm