C++ Tutorial/Function/function parameters

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Change a call-by-value parameter does not affect the argument

#include <iostream> 
using namespace std; 
 
double f(double x); 
 
int main() 
{ 
  double t = 10.0; 
 
  cout << "1/10.0 is " << f(t) << "\n"; 
 
  cout << "Value of t is still: " << t << "\n"; 
 
  return 0; 
} 
 
double f(double x) 
{ 
  x = 1 / x;
  cout << "inside f " << x << "\n"; 
  return x; 
}
inside f 0.1
1/10.0 is 0.1
Value of t is still: 10

Change the contents of an array using a function

#include <iostream> 
using namespace std; 
 
void f(int *n, int num); 
 
int main() 
{ 
  int i, nums[10]; 
 
  for(i=0; i < 10; i++) nums[i] = i+1; 
 
  cout << "Original contents: "; 
  for(i=0; i < 10; i++) cout << nums[i] << " "; 
  cout << "\n"; 
 
  f(nums, 10); // compute cubes 
 
  cout << "Altered contents: "; 
  for(i=0; i<10; i++) cout << nums[i] << " "; 
 
  return 0; 
} 
 
void f(int *n, int num) 
{ 
  while(num) { 
    *n = *n * *n ; 
    num--; 
    n++; 
  } 
}
Original contents: 1 2 3 4 5 6 7 8 9 10
Altered contents: 1 4 9 16 25 36 49 64 81 100

Declare int array parameter for a function without indicating the array length

#include <iostream> 
using namespace std; 
 
void display(int num[]); 
 
int main() 
{ 
  int t[10], i; 
 
  for(i=0; i < 10; ++i) t[i]=i; 
 
  display(t); // pass array t to a function 
 
  return 0; 
} 
 

void display(int num[]) 
{ 
  int i; 
 
  for(i=0; i < 10; i++) cout << num[i] << " "; 
}
0 1 2 3 4 5 6 7 8 9

Define function to accept three int parameters

#include <iostream> 
using namespace std; 
 
void box(int length, int width, int height); // box()"s prototype 
 
int main() 
{ 
  box(7, 20, 4); 
  box(50, 3, 2); 
  box(8, 6, 9); 
 
  return 0; 
} 
 
void box(int length, int width, int height) 
{ 
  cout << "volume of box is " << length * width * height << "\n"; 
}
volume of box is 560
volume of box is 300
volume of box is 432

Demonstrate the pointer version of swap(): Exchange the values of the variables pointed to by x and y

#include <iostream> 
using namespace std; 
 
void swap(int *x, int *y); 
 
int main() 
{ 
  int i, j; 
 
  i = 10; 
  j = 20; 
 
  cout << "Initial values of i and j: "; 
  cout << i << " " << j << "\n"; 
 
  swap(&j, &i); // call swap() with addresses of i and j 
 
  cout << "Swapped values of i and j: "; 
  cout << i << " " << j << "\n"; 
 
  return 0; 
} 
 
void swap(int *x, int *y) 
{ 
  int temp; 
 
  temp = *x;
  *x = *y;  
  *y = temp;
}
Initial values of i and j: 10 20
Swapped values of i and j: 20 10

Function parameter: Use int pointer to accept an array

#include <iostream> 
using namespace std; 
 
void display(int num[]); 
 
int main() 
{ 
  int t[10], i; 
 
  for(i=0; i < 10; ++i) t[i]=i; 
 
  display(t); // pass array t to a function 
 
  return 0; 
} 
 
void display(int *num) 
{ 
  int i; 
 
  for(i=0; i < 10; i++) cout << num[i] << " "; 
}
0 1 2 3 4 5 6 7 8 9

Handling an array parameter as a pointer

#include <iostream>
using std::cout;
using std::endl;
double average(double* array, int count);     
int main() {
  double values[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
  cout << "Average = "<< average(values, (sizeof values)/(sizeof values[0]))<< endl;
  return 0;
}
double average(double* array, int count) {
  double sum = 0.0;                           
  for(int i = 0 ; i < count ; i++)
    sum += *array++;                          
  return sum/count;                           
}
Average = 5.5

Pass a pointer to a function.

#include <iostream> 
using namespace std; 
 
void f(int *j);
 
int main() 
{ 
  int i; 
  int *p; 
 
  p = &i; 
 
  f(p);   // pass a pointer 
 
  cout << i;
 
  return 0; 
} 
 
void f(int *j) 
{ 
  *j = 100; 
}
100

Pass a string to a function: Invert the case of the letters within a string

#include <iostream> 
#include <cstring> 
#include <cctype>  
using namespace std; 
 
void f(char *str); 
 
int main() 
{ 
  char str[80]; 
 
  strcpy(str, "ABCD"); 
 
  f(str); 
 
  cout << str; 
  return 0; 
} 
 
 
void f(char *str) 
{ 
  while(*str) { 
    if(isupper(*str)) 
        *str = tolower(*str);  
    else if(islower(*str)) 
        *str = toupper(*str); 
    str++; 
  } 
}
abcd

Passing an array to a function

#include <iostream>
using std::cout;
using std::endl;
double average(double array[], int count);    
int main() {
  double values[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
  cout << "Average = "
       << average(values, (sizeof values)/(sizeof values[0]))
       << endl;
  return 0;
}
double average(double array[], int count) {
  double sum = 0.0;                        
  for(int i = 0 ; i < count ; i++)
    sum += array[i];                       
  return sum/count;                        
}
Average = 5.5

Passing a two-dimensional array to a function

#include <iostream>
using std::cout;
using std::endl;
double f(double values[][4], int n);
int main() {
  double beans[3][4] = {
                         { 1.0,  2.0,  3.0,  4.0},
                         { 5.0,  6.0,  7.0,  8.0},
                         { 9.0, 10.0, 11.0, 12.0}
                       };
  cout << f(beans, sizeof beans/sizeof beans[0])<< endl;
  return 0;
}
double f(double array[][4], int size) {
  double sum = 0.0;
  for(int i = 0 ; i < size ; i++)       
    for(int j = 0 ; j < 4 ; j++)        
      sum += array[i][j];
  return sum;
}
78

Passing int by value

#include <iostream>
 
 void swap(int x, int y);
 
 int main()
 {
     int x = 5, y = 10;
     std::cout << "Main. Before swap, x: " << x << " y: " << y << "\n";
     swap(x,y);
     std::cout << "Main. After swap, x: " << x << " y: " << y << "\n";
     return 0;
 }
 
 void swap (int x, int y)
 {
     int temp;
     std::cout << "Swap. Before swap, x: " << x << " y: " << y << "\n";
     temp = x;
     x = y;
     y = temp;
     std::cout << "Swap. After swap, x: " << x << " y: " << y << "\n";
 }
Main. Before swap, x: 5 y: 10
Swap. Before swap, x: 5 y: 10
Swap. After swap, x: 10 y: 5
Main. After swap, x: 5 y: 10

Pass int array to a function

#include <iostream> 
using namespace std; 
 
void display(int num[10]); 
 
int main() 
{ 
  int t[10], i; 
 
  for(i=0; i < 10; ++i) t[i]=i; 
 
  display(t); // pass array t to a function 
 
  return 0; 
} 
 
void display(int num[10]) 
{ 
  int i; 
 
  for(i=0; i < 10; i++) cout << num[i] << " "; 
}
0 1 2 3 4 5 6 7 8 9

Pass variable address to a function

#include <iostream> 
using namespace std; 
 
void f(int *j); 
 
int main() 
{ 
  int i; 
 
  f(&i);  
 
  cout << i; 
 
  return 0; 
} 
    
void f(int *j) 
{ 
  *j = 100; // var pointed to by j is assigned 100 
}
100

the use of ... and its support macros va_arg, va_start, and va_end

#include <stdio.h>
#include <stdarg.h>
#include <string>
void vsmallest(char *message, ...);
int main()
{
 vsmallest("Print %d integers, %d %d %d",10,4,1);
 return(0);
}
void vsmallest(char *message, ...)
{
 int inumber_of_percent_ds=0;
 va_list type_for_ellipsis;
 int ipercent_d_format = "d";
 char *pchar;
 pchar=strchr(message,ipercent_d_format);
  
 while(*++pchar != "\0") {
   pchar++;
   pchar=strchr(pchar,ipercent_d_format);
   inumber_of_percent_ds++;
 }
 printf("print %d integers,",inumber_of_percent_ds);
 va_start(type_for_ellipsis,message);
 while(inumber_of_percent_ds--)
   printf(" %d",va_arg(type_for_ellipsis,int));
 va_end(type_for_ellipsis);
}

Use array as function"s parameter

#include <iostream.h>
float Total(float a[],int num);
const int SIZE = 10;
main()
{
       float * f = new float [SIZE];
       for (int i=0;i<SIZE;i++)
               f[i]=i+i;  //*(f+i)
       cout <<"Sum = "  << Total( f ,SIZE) <<endl;
       cout << "Average = " << Total(f,SIZE)/SIZE;
       delete []f;
       return 0 ;
}
float Total(float a[],int num)
{
       int i;
       float sum = 0;
       for (i=0; i<num ; i++)
               sum += a[i];
       return sum;
}
Sum = 90
Average = 9"

Using reference parameters

#include <iostream>
using std::cout;
using std::endl;
int larger(int& m, int& n);
int main() {
  int value1 = 10;
  int value2 = 20;
  cout << endl << larger(value1, value2) << endl;
  return 0;
}
int larger(int& m, int& n) {
  return m > n ? m : n;
}
20

var args has to be the last one

#include <cstdio>
#include <cstdarg>
#include <iostream>
using namespace std;
bool debug = false;
void debugOut(char* str, ...)
{
  va_list ap;
  if (debug) {
    va_start(ap, str);
    vfprintf(stderr, str, ap);
    va_end(ap);
  }
}
void printInts(int num, ...)
{
  int temp;
  va_list ap;
  va_start(ap, num);
  for (int i = 0; i < num; i++) {
    temp = va_arg(ap, int);
    cout << temp << " ";
  }
  va_end(ap);
  cout << endl;
}
int main(int argc, char** argv)
{
  debug = true;
  debugOut("int %d\n", 5);
  debugOut("String %s and int %d\n", "hello", 5);
  debugOut("Many ints: %d, %d, %d, %d, %d\n", 1, 2, 3, 4, 5);
  printInts(5, 5, 4, 3, 2, 1);
  return (0);
}