Udostępnij za pośrednictwem


Small Basic - Creating Different Variables

Variables in Small Basic are typeless, which means you don’t need to set the type of the data you’re going to store in a variable. Small Basic would actually let you use the same variable to store integers, decimal numbers, strings, or even object identifiers, but doing that would make your program confusing!

 

Instead, you should always create different variables to store the different values. Each variable should have one purpose so that you can name it clearly and make its purpose easy for you (and anyone who sees your code) to understand. For example, if you define a variable named score to save a player’s score in a game, you should only use that variable for that one purpose. If you figure out later that you need to store the player’s email address to send a congratulatory message when he wins, then create a new variable. The Listing shows why you should avoid having one variable store different data types. 

Listing:

'BadStyle.sb

'Uses the same variable to store different data types.

3

4  x = 5

5  TextWindow.WriteLine(x)

6  x = 5.326

7  TextWindow.WriteLine(x)

8  x = "How are you doing?"

9  TextWindow.WriteLine(x)

 

Output:

5

5.326

How are you doing?

 

First, the program assigns the integer 5 to the variable x (Line 4). It then assigns the decimal number 5.326 to x (Line 6). After that, it assigns the string "How are you doing?" to the same variable (Line 8). We break this problem down step-by-step in the Figure. 

Figure: How a variable in Small Basic can refer to different data types

Instead of using one variable to store all these data types, you could use score to store the score integer, interestRate to store a floating-point interest rate, and question to store a string (the question you want to ask).

 

SELF-CHECK:

The following program makes no sense, but Small Basic runs it and displays the number 0 as the output.

Explain how Small Basic gets 0 from this code:

x = 5

y = "How are you doing?"

z = y/x

TextWindow.WriteLine(z)

 

Post any questions below! And...

Head to https://blogs.msdn.com/SmallBasic to download Small Basic and learn all about it!

 

Small and Basically yours,

   - Ninja Ed & Majed Marji

Comments