A variable is a named item used to hold a value. This can be an actual value or an address that points to where a value is stored. If the variable holds an address that points to a place a value is stored it is a pointer.
All variables need to be assigned a value to work, on occasion a value will automatically be assigned to the variable, but that will depend on the variable. You assign a value with the ‘=’ sign. You should be reading this symbol in code as ‘assigned’, not ‘equal to’. (When it is by itself, ‘==’ is checking for equality).
A variable declaration is just where you are declaring that a variable of datatype exists. For example:
datatype varName;
In the above example, while a variable of datatype has been made it has not yet been assigned a value, you will also notice that it is using the camel case naming convention, which will be explained in a different post.
A expression is a number, a variable, or a calculation. Simply put it’s something that will simplify to a value. An assignment statement is when a variable is assigned a value, whether it already had a value stored in it or not. As such an assignment statement has a left value and a right value. The left value is the variable, it’s the location at which you will be storing the right value. The right value is an expression it is the value that will be stored in the location on the left side. When the right value datatype doesn’t match the left value datatype there can be errors, either in terms of something like rounding or an actual compiler error. An example of an assignment statement is:
varName = expression;
You can also initialize a variable. This is when you declare a variable and assign it a value in the same line. For example:
datatype varName = expression;
The rules for a variable name (also known as an identifier) are:
- Must be a sequance of letters, underscores and numbers
- Must start with a letter or a underscore
- This means that it cant start with a number
- They can’t be a reserved word
- a identifier can only be declared once in the same scope
- Identifiers are case sensative
A scope is where a variable is defined. For example, if you declare a variable at the beginning of a function the scope of that variable is that entire function, while if you were to declare it in an if statement or a while loop it would only be defined in the while loop or if statement.
Related posts:(coming soon)
- Naming conventions
- More on scopes
- Arithmetic expressions
- More on avoiding type mismatches(Type casting/conversion)