Skip to main content Skip to navigation

2. Variables and Constants

1. Data types

When declaring constants and variables, you will always have to declare the type. There are only a few basic datatypes in f90

character 'x' or "x"
integer 365
real 2.718 or 1.4E-03
complex (2.0,3.5)

Back to top

2. Variable declarations

Variables must be declared in the code before they are used. The declaration syntax starts with the type, then two colons, and then followed by one or more variables, with each variable separated by a comma, e.g.

integer :: big,small,medium

This declares three variables of integer type, called "big", "small" and "medium".

There are restrictions on what names you can use for variables in f90. Your variable names should always start with a letter of the alphabet. Just link in linux file names, you can't have whitespace in variable names, but you can use underscores. Try to avoid special characters. f90 is not case-sensitive though, so variable names ELEMENT, Element and element are all treated as the same variable name.

Variables can also have values assigned to them at declaration time, just use an equals sign, e.g.

 real :: element = 1.3E2

Character declarations are a little different. You have to also include the length of the string (len=) that you'd like to use - this is a maximum length, so you can have a string of size less than or equal to the specifed length, e.g. to declare a character variable called string and set it to the value 'skywalker' we would have to use the following:

 
         character(len=12) :: string = 'skywalker'
        

Whitespace will be preserved inside a string that is enclosed by quotation marks

parameter definitions follow a very similar pattern, e.g.

 
real, parameter :: pi = 3.14159
        

If you declare a variable without immediately assigning a value to it, you can always assign a value later in the code. The assignment statement is an equals sign (=), such that the value on the right of the equals sign is mapped onto the value to the left of the equals sign

Putting it into Practice:

In this example, edit your existing code to include some declarations. Follow the example of the code below;
PROGRAM Hello
IMPLICIT NONE
integer :: special
character(len=12) :: name = 'organa'
! print out your variables/constants

special = 5
print*,special
print*
print*,name

END PROGRAM Hello
Make sure your code compiles and prints out the correct value.

Back to top

3. Reserved words

You should make sure that none of your variable or constant names are things like integer, real, character and so on. Clearly these are reserved words in f90 and have a special purpose.

Back to top