Where

Statement Purpose

The where statement was introduced in FORTRAN 90 to aid in operations involving arrays. It provides a way to mask the assignment of arrays or the evaluations of arrays. This means that it provides a way to use some logical expression to control what array elements are assigned values in an operation that would normally assign values to all elements of the array.

Rules and examples of use

When manipulating large arrays, it is sometimes necessary to mask some of the operations that you are preforming on them. The best way to explain this function is to analyze an example. Lets say that you want to take an array and transform its values into their reciprocal values. You could do this simply by typing the following do loop.
		Do i=1,n
		  a(i)= 1.0/a(i)
		End do
This loop would work fine, except where an element of "a" originally was equal to zero. This would mean you were dividing by zero in the mathematical expression. To prevent this, the where statement can be used in the following manner.
		where (a.neq.0.0)
			a = 1.0/a
		end where
As you can see the logical expression tells the compiler to execute the mathematical expression only where the elements of the array "a" are not equal to zero. Also, notice that no array bounds need to be specified when using a where construct, although you can use range specifiers (e.g. a(2:11)) if necessary. This is because the where statement only works on array arguments. It is automatically assumed that whatever variables are used in a where construct were previously declared as arrays. Also, the where construct can be extended further by using the ELSEWHERE statement. The elsewhere statement will give the computer an option on what to do if the logical expression in the where expression evaluates to be false. There can only be one elsewhere statement inside of a where block because you can only have two possibilities, when the where statement is true and where it is false. So in the case of the above example, I could make the elements in a that equaled zero to be equal to 1.1 when I evaluated the reciprocal by typing the following.
		where (a.neq.0.0)
			a = 1.0/a
		elsewhere
			a = 1.1
		end where
As a final caution, do not confuse the where construct with an if construct. The syntax is similar between the two, but that is where the similarities end. The where construct can only accommodate two possible outcomes, where a block if construct can accommodate multiple outcomes through the use of many else if statements. Also, if statements can be used in conjunction with all kinds of variables, where as the where construct can only be used to assign values to variables that have been declared to be arrays.

For additional information and examples see

lecture nineteen

example: where.f

Up one level / Home


Written by Jason Wehr: jcw142@psu.edu and Maintained by John Mahaffy : jhm@cac.psu.edu