I do some programming in Fortran and some in C, and I think that the C preprocessor can be pretty nifty in its flexibility of adding or hiding code with preprocessing constants. I don't know of any way to do this with Fortran, but I'm curious: does the Fortran compiler detect code that can be removed at compile time?
Take this as an example:
program test_branch
implicit none
logical, parameter :: echo = .false.
integer :: n, sum
sum = 0
do n=1,100
sum = sum + n**2
if (echo) then
print *, "Sum:", sum
end if
end do
end program test_branch
The value of echo will never change, but if the compiler doesn't realize this, it will still be checking for a branch each time, as well as including dead, unreachable code in the executable. Obviously this isn't a very big difference, especially with branch prediction, but I'm wondering if expressions like that can be added and literally not cost anything. Is there an optimization setting that does this, or might it be done by default?
Both Fortran and C compilers may (but do not have to) optimize by removing dead code.
Notice that optimization is a compiler thing. The language specification only tells what optimizations could or cannot do.
If you use GCC (ie gfortran
for Fortran code, and gcc
for C code) the optimizations are often the same, since both compilers have different front-ends but a common middle-end and a common back-end. Their optimization would work on a very similar internal representation, if you code the same algorithm in Fortran and in C.
And GCC does not optimize if not asked to. You want to pass something like -Wall -O2
as gcc
or gfortran
compiler options.