03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

2.6. FUNCTIONS 39<br />

case 3: v[i] = w[i] + x[i]; i++;<br />

case 2: v[i] = w[i] + x[i]; i++;<br />

case 1: v[i] = w[i] + x[i];<br />

case 0: ;<br />

}<br />

This technique is called Duff’s device. Although this is an interesting technique to realize an<br />

iterative computation without a loop, the per<strong>for</strong>mance impact is probably limited in practice.<br />

Such technique should be only considered in program parts with a significant fraction on the<br />

overall run time; otherwise readability of sources is more important.<br />

2.5.7 Goto<br />

DO NOT USE IT. NEVER! EVER!<br />

2.6 Functions<br />

Functions are important building blocks of C ++ programs. The first example we have seen is<br />

the main function in the hello-world program. main must be present in every executable and is<br />

called when the program starts. Other than that there is noting special about main.<br />

The general <strong>for</strong>m of a C ++ function is:<br />

[inline] return type function name (argument list)<br />

{<br />

body of the function<br />

}<br />

For instance, one can be implement a very simple function to square a value:<br />

double square(double x)<br />

{<br />

return x ∗ x;<br />

}<br />

In C and C ++ each function has a return type. A function that does not return a value has the<br />

pseudo-return-type “void”:<br />

void print(double x)<br />

{<br />

std::cout ≪ ”x is ” ≪ x ≪ ’\n’;<br />

}<br />

void is not a real type but moreover a placeholder that enables us to omit returning a value.<br />

We cannot define objects of it:<br />

void nothing; // error

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!