Declaration Statement1

Declaration Statement1 - A way to avoid this would be to...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Declaration Statements Suppose that you have a function to compute factorials (1 x 2 x . .. N): double fact(int n) { double f = 1.0; int i; for (i = 2; i <= n; i++) f *= (double)i; return f; } and you need to use this factorial function to initialize a constant in another function, after doing some preliminary checks on the function parameters to ensure that all are greater than zero. In C you can approach this a couple of ways. In the first, you would say: /* return -1 on error, else 0 */ int f(int a, int b) { const double f = fact(25); if (a <= 0 || b <= 0) return -1; /* use f in calculations */ return 0; } This approach does an expensive computation each time, even under error conditions.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: A way to avoid this would be to say: /* return -1 on error, else 0 */ int f(int a, int b) { const double f = (a &lt;= 0 || b &lt;= 0 ? 0.0 : fact(25)); if (a &lt;= 0 || b &lt;= 0) return -1; /* use f in calculations */ return 0; } but the logic is a bit torturous. In C++, using declaration statements (see above), this problem can be avoided entirely, by saying: /* return -1 on error, else 0 */ int f(int a, int b) { if (a &lt;= 0 || b &lt;= 0) return -1; const double f = fact(25); /* use f in calculations */ return 0; }...
View Full Document

Page1 / 2

Declaration Statement1 - A way to avoid this would be to...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online