Computational Physics - Department of Physics

(Axel Boer) #1

36 2 Introduction to C++ and Fortran


Address of the matrix element matr[1]: 0xbfffef70
Value of the matrix element matr[1]; 321
Address of the matrix element matr[2]: 0xbfffef74
Value of the matrix element matr[2]: 322
Value of the pointer: 0xbfffef70
The value pointer points at: 321
The value that (pointer+1) points at: 322
Address of the pointer variable : 0xbfffef6c

2.5.3 Macros in C++


In C we can define macros, typically global constants or functions through thedefinestate-
ments shown in the simple C-example below for



  1. #define ONE 1

  2. #define TWO ONE + ONE

  3. #define THREE ONE + TWO



  4. main()

  5. {

  6. printf("ONE=%d, TWO=%d, THREE=%d",ONE,TWO,THREE);

  7. }


In C++ the usage of macros is discouraged and you should rather use the declaration
for constant variables. You would then replace a statement like #define ONE 1 with
const int ONE = 1;. There is typically much less use of macros in C++ than in C. C++
allows also the definition of our own types based on other existing data types. We can do this
using the keyword typedef, whose format is: typedef existing_type new_type_name ;,
where existing_type is a C++ fundamental or compound type and new_type_name is the
name for the new type we are defining. For example:


typedef charnew_name;
typedef unsigned intword ;
typedef char*test;
typedef charfield [50];


In this case we have defined four data types: new_name, word, test and field as char, unsigned
int, char* and char[50] respectively, that we could perfectly use in declarations later as any
other valid type


new_name mychar, anotherchar,*ptc1;
word myword;
test ptc2;
field name;


The use of typedef does not create different types. It only creates synonyms of existing types.
That means that the type ofmywordcan be considered to be either word or unsigned int,
since both are in fact the same type. Using typedef allows to define an alias for a type that is
frequently used within a program. It is also useful to define types when it is possible that we
will need to change the type in later versions of our program,or if a type you want to use has
a name that is too long or confusing.
In C we could define macros for functions as well, as seen below.

Free download pdf