Computational Physics - Department of Physics

(Axel Boer) #1

10 2 Introduction to C++ and Fortran


Table 2.1Examples of variable declarations for C++ and Fortran. We reserve capital letters for Fortran
declaration statements throughout this text, although Fortran is not sensitive to upper or lowercase letters.
Note that there are machines which allow for more than 64 bitsfor doubles. The ranges listed here may
therefore vary.


type in C++ and Fortran bits range
int/INTEGER (2) 16 − 32768 to 32767
unsigned int 16 0 to 65535
signed int 16 − 32768 to 32767
short int 16 − 32768 to 32767
unsigned short int 16 0 to 65535
signed short int 16 − 32768 to 32767
int/long int/INTEGER(4) 32 − 2147483648 to 2147483647
signed long int 32 − 2147483648 to 2147483647
float/REAL(4) 32 10 −^44 to 10 +^38
double/REAL(8) 64 10 −^322 to 10 e+^308

The following list may help in clarifying the above points:

type of variable validity
local variables defined within a function, only available within the
scope of the function.
formal parameter If it is defined within a function it is only available within
that specific function.
global variables Defined outside a given function, available for all func-
tions from the point where it is defined.

In Table 2.1 we show a list of some of the most used language statements in Fortran and
C++.
In addition, both C++ and Fortran allow for complex variables. In Fortran we would declare
a complex variable asCOMPLEX (KIND=16):: x, ywhich refers to a double with word length
of 16 bytes. In C++ we would need to include a complex library through the statements


#include
complex x, y;


We will discuss the above declaration complex x,y;in more detail in chapter 3.


2.1.1 Scientific hello world


Our first programming encounter is the ’classical’ one, found in almost every textbook on
computer languages, the ’hello world’ code, here in a scientific disguise. We present first the
C version.


http://folk.uio.no/mhjensen/compphys/programs/chapter02/cpp/program1.cpp
/comments in C begin like this and end with/
#include <stdlib.h> /atof function/
#include <math.h> /sine function /
#include <stdio.h> /printf function/


intmain (intargc,char*argv[])
{

Free download pdf