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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

2.6. FUNCTIONS 41<br />

It should be mentioned here that the inline keyword is not mandatory. The compiler can decide<br />

against inlining <strong>for</strong> the reasons given in the previous paragraph. On the other hand, the compiler<br />

is free to inline functions without the inline keyword.<br />

For obvious reasons, the definition of an inline function must be visible in every compile unit<br />

where it is called. In contrast to other functions, it cannot be compiled separately. Conversely,<br />

a non-inline function cannot be visible in multiple compile units because it collides when the<br />

compiled parts are ‘linked’ together. Thus, there are two ways to avoid such collisions: assuring<br />

that the function definition is only present in one compile unit or declaring the function as<br />

inline.<br />

2.6.2 Function Arguments<br />

If we pass an argument to a function it creates by default a copy. For instance, the following<br />

would not work (as expected):<br />

void increment(int x)<br />

{<br />

x++;<br />

}<br />

int main()<br />

{<br />

int i= 4;<br />

increment(i);<br />

cout ≪ ”i is ” ≪ i ≪ ’\n’;<br />

}<br />

The output would be 4. The operation x++ in the second line only increments a local copy but<br />

not the original value. This kind of argument transfer is called ‘call-by-value’ or ‘pass-by-value’.<br />

To modify the value itself we have to ‘pass-by-reference’ the variable:<br />

void increment(int& x)<br />

{<br />

x++;<br />

}<br />

Now the variable itself is increment and the output will be 5 as expected. We will discuss<br />

references more detailed in § 2.10.2.<br />

Temporary variables — like the result of an operation — cannot be passed by reference:<br />

increment(i + 9); // error<br />

We could not compute (i + 9)++ anyway. In order to call such a function with some temporary<br />

value one needs to store it first in a variable and pass this variable to the function.<br />

Larger data structures like vectors and matrices are almost always passed by reference <strong>for</strong><br />

avoiding expensive copy operations:<br />

double two norm(vector& v) { ... }<br />

An operation like a norm should not change its argument. But passing the vector by reference<br />

bears the risk of accidentally overwriting it.

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

Saved successfully!

Ooh no, something went wrong!