# Lec12 - Lecture 12: Passing to Functions PIC 10A Todd...

This preview shows pages 1–4. Sign up to view the full content.

1 Lecture 12: Passing to Functions PIC 10A Todd Wittman A Comment on Comments When commenting your homework, QUANTITY QUALITY !!! Some students are commenting every line of code, but the comments are mostly meaningless. int x = 1; //Sets integer x=1. while ( x < 20 ) { //This is a while loop. cout << x << “ “; //Outputs x and “ “. x = x + 2; //Adds 2 to x. } //Ends the while loop. Comments are meant to help the reader understand the code, not make it harder to understand!

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

View Full Document
2 A Comment on Comments Would have been much better to just comment on the block of code, rather than commenting every line. // Print out the odd numbers 1 through 19. int x = 1; while ( x < 20 ) { cout << x << “ “; x = x + 2; } You were told it’s OK to over-comment your HW, but this assumes you write worthwhile comments. Sec 4.4 : Return Values Your function should always return something, unless it’s a void. For example, a square root is only defined for non-negative numbers (in the real numbers). One root of the quadratic formula is: double compute1Root (double a, double b, double c) { if ( b*b - 4*a*c >= 0 ) return (-b+sqrt(b*b-4*a*c))/(2*a); } But this returns nothing for if b*b-4*a*c < 0. Not good! double compute1Root (double a, double b, double c) { if ( b*b - 4*a*c >= 0 ) return (-b+sqrt(b*b-4*a*c))/(2*a); return 0; } a ac b b x 2 4 2 - + - = Default return value. Could be anything you want.
3 Function Declarations Last lecture we mentioned that all functions have to be written before the main routine, because C++ reads the code top to bottom. When you have multiple functions and functions calling other functions, they should be listed in reverse order in which they’re called. This can get tricky for complex programs. One way around this is to declare your functions right after the namespace line. void my_function (double x, int y, string s); The declaration looks just like the prototype starting the function, except with a semi-colon. Two Ways to Make Functions Work

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 04/27/2010 for the course PIC 157-050-21 taught by Professor Wittman during the Fall '10 term at UCLA.

### Page1 / 11

Lec12 - Lecture 12: Passing to Functions PIC 10A Todd...

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

View Full Document
Ask a homework question - tutors are online