CP1_7d_Functions4_1112

# CP1_7d_Functions4_1112 - Programmer-defined...

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

Programmer-defined Functions (cont.)

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

View Full Document
Print the winner void print winner( int my score, int your score ); int main() { int my_score, your_score; cin >> my_score >> your_score; print_winner(my_score, your_score); return 0; } 2 CSIS1117B Computer Programming 1 2011-2012
You never win!! void print_winner( int my_score, int your_score ) { f ( our score my score ( y_ y_ ) { //you will never beat me!! int temp = my score; 90 70 My score: 90 our score: 70 my_score = your_score; your_score = temp; } Your score: 70 I win!!!!! cout << "My score: " << my_score << endl; cout << "Your score: " << your_score << endl; 70 90 My score: 90 if ( my_score > your_score ) cout << "I win!!!!!" << endl; Your score: 70 I win!!!!! else if ( your_score > my_score ) cout << "You win" << endl; else out < "It's a draw" << ndl 3 CSIS1117B Computer Programming 1 2011-2012 cout << "It's a draw" << endl; }

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

View Full Document
Make a function to do the swap void swap( int i, int j ) { nt temp = p ; i=j; j = temp; } 90 70 My score: 90 our score: 70 void print_winner( int my_score, int your_score ) { Your score: 70 I win!!!!! if ( your_score > my_score ) { //you will never beat me!! 70 90 My score: 70 swap( my_score, your_score ); } Your score: 90 You win cout << "My score: " << my_score << endl; cout << "Your score: " << your_score << endl; / rest of code unchanged 4 CSIS1117B Computer Programming 1 2011-2012 // rest of code unchanged
Why didn't it work? From our previous class: Parameters are local variables of their functions. When a function is invoked with arguments, the value of the arguments are used to initialize the corresponding formal parameters. This process is known as call-by-value. If the value of a parameter is changed by statements in the body of the function, the value of the argument is not affected. The argument was used only to provide an initial alue for the parameter 5 CSIS1117B Computer Programming 1 2011-2012 value for the parameter.

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

View Full Document
Call-by-value The parameters i and j are value parameters .
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 12/15/2011 for the course CSIS 1117B taught by Professor Noneedtoknow during the Winter '11 term at HKU.

### Page1 / 15

CP1_7d_Functions4_1112 - Programmer-defined...

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

View Full Document
Ask a homework question - tutors are online