Even though C/C++ uses call by value for passing parameters, you can create a
call by reference by passing a pointer to an argument, instead of the argument itself.
Since the address of the argument is passed to the function, code within the function
can change the value of the argument outside the function.
Pointers are passed to functions just like any other value. Of course, you need
to declare the parameters as pointer types. For example, the function swap() , which exchanges the values of the two integer variables pointed to by its arguments,
shows how.
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */
}
swap() is able to exchange the values of the two variables pointed to by x and y
because their addresses (not their values) are passed. Thus, within the function,
the contents of the variables can be accessed using standard pointer operations, and
the contents of the variables used to call the function are swapped.
Remember that swap() (or any other function that uses pointer parameters) must
be called with the addresses of the arguments. The following program shows the correct
way to call swap() :
void swap(int *x, int *y);
int main(void)
{
int i, j;
i = 10;
j = 20;
swap(&i, &j); /* pass the addresses of i and j */
return 0;
}
In this example, the variable i is assigned the value 10 and j is assigned the value
20. Then swap() is called with the addresses of i and j. (The unary operator & is used
to produce the address of the variables.) Therefore, the addresses of i and j, not their
values, are passed into the function swap() .
Note :C++ allows you to fully automate a call by reference through the use of reference
parameters. This feature is described in Part Two.
C C++ Source Codes, C C++ Practical examples ,C C++ tutorial ,Your best resource for Learning C and C++
Showing posts with label a. Show all posts
Showing posts with label a. Show all posts
Wednesday, September 29, 2010
Monday, September 27, 2010
The return Statement : Returning from a Function
The return statement itself is described in Chapter 3. As explained, it has two important
uses. First, it causes an immediate exit from the function that it is in. That is, it causes
program execution to return to the calling code. Second, it may be used to return a
value. This section examines how the return statement is used.
uses. First, it causes an immediate exit from the function that it is in. That is, it causes
program execution to return to the calling code. Second, it may be used to return a
value. This section examines how the return statement is used.
Returning from a Function
There are two ways that a function terminates execution and returns to the caller. The
first occurs when the last statement in the function has executed and, conceptually,
the function's ending curly brace (}) is encountered. (Of course, the curly brace isn't
actually present in the object code, but you can think of it in this way.) For example, the
pr_reverse() function in this program simply prints the string "I like C++" backwards
on the screen and then returns.
#include <string.h>
#include <stdio.h>
void pr_reverse(char *s);
int main(void)
{
pr_reverse("I like C++");
return 0;
}
void pr_reverse(char *s)
{
register int t;
for(t=strlen(s)-1; t>=0; t--) putchar(s[t]);
}
Once the string has been displayed, there is nothing left for pr_reverse() to do, so it
returns to the place from which it was called.
Actually, not many functions use this default method of terminating their
execution. Most functions rely on the return statement to stop execution either
because a value must be returned or to make a function's code simpler and more
efficient.
A function may contain several return statements. For example, the find_substr()
function in the following program returns the starting position of a substring within
a string, or returns −1 if no match is found.
#include <stdio.h>
int find_substr(char *s1, char *s2);
int main(void)
{
if(find_substr("C++ is fun", "is") != -1)
printf("substring is found");
actually present in the object code, but you can think of it in this way.) For example, the
pr_reverse() function in this program simply prints the string "I like C++" backwards
on the screen and then returns.
#include <string.h>
#include <stdio.h>
void pr_reverse(char *s);
int main(void)
{
pr_reverse("I like C++");
return 0;
}
void pr_reverse(char *s)
{
register int t;
for(t=strlen(s)-1; t>=0; t--) putchar(s[t]);
}
Once the string has been displayed, there is nothing left for pr_reverse() to do, so it
returns to the place from which it was called.
Actually, not many functions use this default method of terminating their
execution. Most functions rely on the return statement to stop execution either
because a value must be returned or to make a function's code simpler and more
efficient.
A function may contain several return statements. For example, the find_substr()
function in the following program returns the starting position of a substring within
a string, or returns −1 if no match is found.
#include <stdio.h>
int find_substr(char *s1, char *s2);
int main(void)
{
if(find_substr("C++ is fun", "is") != -1)
printf("substring is found");
return 0;
}
/* Return index of first match of s2 in s1. */
int find_substr(char *s1, char *s2)
{
register int t;
char *p, *p2;
for(t=0; s1[t]; t++) {
p = &s1[t];
p2 = s2;
while(*p2 && *p2==*p) {
p++;
p2++;
}
if(!*p2) return t; /* 1st return */
}
return -1; /* 2nd return */
}
}
/* Return index of first match of s2 in s1. */
int find_substr(char *s1, char *s2)
{
register int t;
char *p, *p2;
for(t=0; s1[t]; t++) {
p = &s1[t];
p2 = s2;
while(*p2 && *p2==*p) {
p++;
p2++;
}
if(!*p2) return t; /* 1st return */
}
return -1; /* 2nd return */
}
Function :The General Form of a Function in C,C++
Functions are the building blocks of C and C++ and the place where all program
activity occurs. This chapter examines their C-like features, including passing
arguments, returning values, prototypes, and recursion. Part Two discusses
the C++-specific features of functions, such as function overloading and reference
parameters.
activity occurs. This chapter examines their C-like features, including passing
arguments, returning values, prototypes, and recursion. Part Two discusses
the C++-specific features of functions, such as function overloading and reference
parameters.
The General Form of a Function
The general form of a function is
ret-type function-name(parameter list)
{
body of the function
}
The ret-type specifies the type of data that the function returns.Afunction may return
any type of data except an array. The parameter list is a comma-separated list of variable
names and their associated types that receive the values of the arguments when the
function is called.Afunction may bewithout parameters, in which case the parameter
list is empty. However, even if there are no parameters, the parentheses are still required.
In variable declarations, you can declare many variables to be of a common type
by using a comma-separated list of variable names. In contrast, all function parameters
must be declared individually, each including both the type and name. That is, the
parameter declaration list for a function takes this general form:
f(type varname1, type varname2, . . . , type varnameN)
For example, here are correct and incorrect function parameter declarations:
f(int i, int k, int j) /* correct */
f(int i, k, float j) /* incorrect */
Sunday, September 26, 2010
A Tic-Tac-Toe Game Example in C,C++
The longer example that follows illustrates many of the ways that you can manipulate
arrays with C/C++. This section develops a simple tic-tac-toe program.
Two-dimensional arrays are commonly used to simulate board game matrices.
The computer plays a very simple game. When it is the computer's turn, it uses
get_computer_move() to scan the matrix, looking for an unoccupied cell. When it finds
one, it puts an O there. If it cannot find an empty location, it reports a draw game and
exits. The get_player_move() function asks you where you want to place an X. The
upper-left corner is location 1,1; the lower-right corner is 3,3.
The matrix array is initialized to contain spaces. Each move made by the player or
the computer changes a space into either an X or an O. This makes it easy to display the
matrix on the screen.
Each time a move has been made, the program calls the check() function. This
function returns a space if there is no winner yet, an X if you have won, or an O if the
computer has won. It scans the rows, the columns, and then the diagonals, looking for
one that contains either all X's or all O's.
The disp_matrix() function displays the current state of the game. Notice how
initializing the matrix with spaces simplified this function.
The routines in this example all access the matrix array differently. Study them to
make sure that you understand each array operation.
/* A simple Tic Tac Toe game. */
#include <stdio.h>
#include <stdlib.h>
char matrix[3][3]; /* the tic tac toe matrix */
char check(void);
void init_matrix(void);
void get_player_move(void);
void get_computer_move(void);
void disp_matrix(void);
int main(void)
{
char done;
printf("This is the game of Tic Tac Toe.\n");
printf("You will be playing against the computer.\n");
done = ' ';
arrays with C/C++. This section develops a simple tic-tac-toe program.
Two-dimensional arrays are commonly used to simulate board game matrices.
The computer plays a very simple game. When it is the computer's turn, it uses
get_computer_move() to scan the matrix, looking for an unoccupied cell. When it finds
one, it puts an O there. If it cannot find an empty location, it reports a draw game and
exits. The get_player_move() function asks you where you want to place an X. The
upper-left corner is location 1,1; the lower-right corner is 3,3.
The matrix array is initialized to contain spaces. Each move made by the player or
the computer changes a space into either an X or an O. This makes it easy to display the
matrix on the screen.
Each time a move has been made, the program calls the check() function. This
function returns a space if there is no winner yet, an X if you have won, or an O if the
computer has won. It scans the rows, the columns, and then the diagonals, looking for
one that contains either all X's or all O's.
The disp_matrix() function displays the current state of the game. Notice how
initializing the matrix with spaces simplified this function.
The routines in this example all access the matrix array differently. Study them to
make sure that you understand each array operation.
/* A simple Tic Tac Toe game. */
#include <stdio.h>
#include <stdlib.h>
char matrix[3][3]; /* the tic tac toe matrix */
char check(void);
void init_matrix(void);
void get_player_move(void);
void get_computer_move(void);
void disp_matrix(void);
int main(void)
{
char done;
printf("This is the game of Tic Tac Toe.\n");
printf("You will be playing against the computer.\n");
done = ' ';
init_matrix();
do{
disp_matrix();
get_player_move();
done = check(); /* see if winner */
if(done!= ' ') break; /* winner!*/
get_computer_move();
done = check(); /* see if winner */
} while(done== ' ');
if(done=='X') printf("You won!\n");
else printf("I won!!!!\n");
disp_matrix(); /* show final positions */
return 0;
}
/* Initialize the matrix. */
void init_matrix(void)
{
int i, j;
for(i=0; i<3; i++)
for(j=0; j<3; j++) matrix[i][j] = ' ';
}
/* Get a player's move. */
void get_player_move(void)
{
int x, y;
printf("Enter X,Y coordinates for your move: ");
scanf("%d%*c%d", &x, &y);
x--; y--;
if(matrix[x][y]!= ' '){
printf("Invalid move, try again.\n");
get_player_move();
}
else matrix[x][y] = 'X';
}
do{
disp_matrix();
get_player_move();
done = check(); /* see if winner */
if(done!= ' ') break; /* winner!*/
get_computer_move();
done = check(); /* see if winner */
} while(done== ' ');
if(done=='X') printf("You won!\n");
else printf("I won!!!!\n");
disp_matrix(); /* show final positions */
return 0;
}
/* Initialize the matrix. */
void init_matrix(void)
{
int i, j;
for(i=0; i<3; i++)
for(j=0; j<3; j++) matrix[i][j] = ' ';
}
/* Get a player's move. */
void get_player_move(void)
{
int x, y;
printf("Enter X,Y coordinates for your move: ");
scanf("%d%*c%d", &x, &y);
x--; y--;
if(matrix[x][y]!= ' '){
printf("Invalid move, try again.\n");
get_player_move();
}
else matrix[x][y] = 'X';
}
/* Get a move from the computer. */
void get_computer_move(void)
{
int i, j;
for(i=0; i<3; i++){
for(j=0; j<3; j++)
if(matrix[i][j]==' ') break;
if(matrix[i][j]==' ') break;
}
if(i*j==9) {
printf("draw\n");
exit(0);
}
else
matrix[i][j] = 'O';
}
/* Display the matrix on the screen. */
void disp_matrix(void)
{
int t;
for(t=0; t<3; t++) {
printf(" %c | %c | %c ",matrix[t][0],
matrix[t][1], matrix [t][2]);
if(t!=2) printf("\n---|---|---\n");
}
printf("\n");
}
/* See if there is a winner. */
char check(void)
{
int i;
for(i=0; i<3; i++) /* check rows */
if(matrix[i][0]==matrix[i][1] &&
matrix[i][0]==matrix[i][2]) return matrix[i][0];
for(i=0; i<3; i++) /* check columns */
if(matrix[0][i]==matrix[1][i] &&
void get_computer_move(void)
{
int i, j;
for(i=0; i<3; i++){
for(j=0; j<3; j++)
if(matrix[i][j]==' ') break;
if(matrix[i][j]==' ') break;
}
if(i*j==9) {
printf("draw\n");
exit(0);
}
else
matrix[i][j] = 'O';
}
/* Display the matrix on the screen. */
void disp_matrix(void)
{
int t;
for(t=0; t<3; t++) {
printf(" %c | %c | %c ",matrix[t][0],
matrix[t][1], matrix [t][2]);
if(t!=2) printf("\n---|---|---\n");
}
printf("\n");
}
/* See if there is a winner. */
char check(void)
{
int i;
for(i=0; i<3; i++) /* check rows */
if(matrix[i][0]==matrix[i][1] &&
matrix[i][0]==matrix[i][2]) return matrix[i][0];
for(i=0; i<3; i++) /* check columns */
if(matrix[0][i]==matrix[1][i] &&
/* test diagonals */
if(matrix[0][0]==matrix[1][1] &&
matrix[1][1]==matrix[2][2])
return matrix[0][0];
if(matrix[0][2]==matrix[1][1] &&
matrix[1][1]==matrix[2][0])
return matrix[0][2];
return ' ';
}
if(matrix[0][0]==matrix[1][1] &&
matrix[1][1]==matrix[2][2])
return matrix[0][0];
if(matrix[0][2]==matrix[1][1] &&
matrix[1][1]==matrix[2][0])
return matrix[0][2];
return ' ';
}
Generating a Pointer to an Array
You can generate a pointer to the first element of an array by simply specifying the
array name, without any index. For example, given
int sample[10];
you can generate a pointer to the first element by using the name sample. Thus, the
following program fragment assigns p the address of the first element of sample:
int *p;
int sample[10];
p = sample;
You can also specify the address of the first element of an array using the &
operator. For example, sample and &sample[0] both produce the same results.
However, in professionally written C/C++ code, you will almost never see
&sample[0].
array name, without any index. For example, given
int sample[10];
you can generate a pointer to the first element by using the name sample. Thus, the
following program fragment assigns p the address of the first element of sample:
int *p;
int sample[10];
p = sample;
You can also specify the address of the first element of an array using the &
operator. For example, sample and &sample[0] both produce the same results.
However, in professionally written C/C++ code, you will almost never see
&sample[0].
Subscribe to:
Posts (Atom)