Concept Explanation: Variables

Printer-friendly version


In programming, a variable is a labeled section of memory that holds a specific data value. Once we create this variable, the data contained can be referenced multiple times. When you use a variable as a parameter of a function, the value of that variable is passed to the function. In our example, we create the "timer1" variable and set it to 1000. Later, when we set the parameter of our wait1Msec command as "timer1" the effective result is that the wait timer is set to 1000.


A variable declaration has four main elements:


  1. Type: The type of data that is being stored.
    • Integers use "int"
    • Strings use "string"
  2. Label: This allows us to reference the data later. Make sure to use a name that is not already in use elsewhere.
  3. Equals sign: This separates the label from the value.
  4. Value: The data that is being stored in the variable.

Once you have created the variable, you can change the value stored with the same command you used to create the variable. When modifying a variable, RobotC requires that you use the same data type. This behavior means that you don't need to specify type when modifying a variable.

RobotC Rule 5: The type of data stored in a variable is only defined when you create a variable.

While variables are useful, you should only use them when appropriate. Every time you create a variable, a section of system memory is allocated to that variable. The NXT has a limited amount of memory and you should get into the habit of writing the most efficient programs possible. A good rule of thumb is that you should only use variables in the following situations:

  1. You need to use the same data value more than once.
  2. You need to store something for use later.
  3. You want to quickly adjust a parameters.

We'll talk more about variables as we use them.