13.07.2015 Views

BABAR C++ Course Running the Examples - HEPHY

BABAR C++ Course Running the Examples - HEPHY

BABAR C++ Course Running the Examples - HEPHY

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.

Reference argumentsRecursionConsider(ch2/funcarg.C)void swap( int &i1, int &i2) {int temp = i1;i1 = i2;i2 = temp;}int c = 3;int d = 4;swap(c, d);// c == 4 and d == 3• swap() has reference arguments• upon calling f(), it is as if <strong>the</strong> compiler generatedthis code to initialize its argumentsint &i1 = c;int &i2 = d;A function can call itself (ch2/Stirling.C)int stirling(int n, int k) {if (n < k) return 0;if (k == 0 && n > 0) return 0;if (n == k) return 1;return k * stirling(n-1, k) + stirling(n-1, k-1)}• each block (function, if, for, etc.) creates new scope• variables are declared and initialized in a scope anddeleted when execution leaves scopeExercise: write a function that computes factorial ofa number• thus i1 and i2, <strong>the</strong> variables in swap()’s scope,are aliases for <strong>the</strong> caller’s variables.• swap() behaves like Fortran functions• C does not have reference; instead you have to writeextern void swap(int *i1, int *i2);swap(&c, &d);<strong>BABAR</strong> <strong>C++</strong> <strong>Course</strong> 58 Paul F. Kunz<strong>BABAR</strong> <strong>C++</strong> <strong>Course</strong> 59 Paul F. Kunz

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

Saved successfully!

Ooh no, something went wrong!