Computational Physics - Department of Physics

(Axel Boer) #1

12 2 Introduction to C++ and Fortran


returning 0 if success. The operating system stores the return value, and other programs/u-
tilities can check whether the execution was successful or not. The command-line arguments
are transferred to the main function through the statement


intmain (intargc,char*argv[])


The integerargcstands for the number of command-line arguments, set to one in our case,
while argvis a vector of strings containing the command-line arguments with argv[0]
containing the name of the program and argv[1], argv[2], ... are the command-line args,
i.e., the number of lines of input to the program.
This means that we would run the programs asmhjensen@compphys:./myprogram.exe 0.3.
The name of the program enters argv[0]while the text string 0. 2 enters argv[1]. Here we
define a floating point variable, see also below, through the keywordsfloatfor single pre-
cision real numbers and doublefor double precision. The functionatoftransforms a text
(argv[1])to a float. The sine function is declared in math.h, a library which is not automat-
ically included and needs to be linked when computing an executable file.
With the commandprintfwe obtain a formatted printout. Theprintfsyntax is used for
formatting output in many C-inspired languages (Perl, Python, awk, partly C++).
In C++ this program can be written as


// A comment line begins like this in C++ programs
using namespacestd;
#include
#include
#include
intmain (intargc,char*argv[])
{
// convert the text argv[1] to double using atof:
doubler = atof(argv[1]);
doubles = sin(r);
cout <<"Hello, World! sin("<< r <<")="<< s << endl;
// success
return0;
}


We have replaced the call toprintfwith the standard C++ function cout. The header
file iostreamis then needed. In addition, we don’t need to declare variables likerands
at the beginning of the program. I personally prefer howeverto declare all variables at the
beginning of a function, as this gives me a feeling of greaterreadability. Note that we have
used the declarationusing namespace std;. Namespace is a way to collect all functions
defined in C++ libraries. If we omit this declaration on top ofthe program we would have to
add the declarationstdin front ofcoutorcin. Our program would then read


// Hello world code without using namespace std
#include
#include
#include
intmain (intargc,char*argv[])
{
// convert the text argv[1] to double using atof:
doubler = atof(argv[1]);
doubles = sin(r);
std::cout <<"Hello, World! sin("<< r <<")="<< s << endl;
// success
return0;
}

Free download pdf