Hi,
Below is my code. You can see all of the functions are void, but how can these functions call? to clarify my question, please see this example:
we have 5 numbers which can be ordered via below code which are -1 2 3 5 7.
In this program, first function enters numbers.Second one will order them.In this regard, what is the relation between first and second function? If the first function was "int v(int)", it would return numbers to main program and there would be relation between functions, but it is a void and it cannot return any number to main program. So, how can these functions have relations?
#include "stdafx.h"
#include <iostream>
using namespace std;
void v(int [], int);
void p(int [] , int);
void kh(int [],int);
int main(){
const int n=5;
int x[5];
v(x,n);
p(x,n);
kh(x,n);
cin.get();}
//:::::::::::::::::::::::::
void v(int x[], int n){
for(int i=0;i<n;i++)
cin>>x[i];}
void p(int x[], int n){
int t;
for(int i=n-1;i>0;i--){
for(int j=0;j<i;j++)
if(x[j]>x[j+1]){
t=x[j];
x[j]=x[j+1];
x[j+1]=t;}}
}
You pass the array to the functions so it is possible for the functions to read and write to the array. The v function reads input from the user and stores it in the array. The p function sorts the array. The kh function prints the array.
But why is not that true for below code?
Number are 10 and 15 for x and y. first and second cout output 10 and 15. Third one output 11 and 16. And important point is the last one. The last one output 10 and 15. Why function f do not store 11 and 16. This is as same as the last code.
#include "stdafx.h"
#include <iostream>
using namespace std;
void f(int,int);
int main(){
int x,y;
cin>>x>>y;
cout<<"x="<<x<<"y="<<y;
f(x,y);
cout<<x<<y;
cin.get();
cin.get();
//&&&&&&&&&&&&&&&&&&&
void f(int x, int y)
cout<<"\n f receives : x="<<x<<",y="<<y;
x++;
y++;
cout<<"new values from f: x="<<x<<:,y="<<y;
By default arguments are passed by value, meaning the function will receive a copy. Modifying the copy will not have an impact on the variables that was passed to the function. That is why modifying x and y inside f will not change the variables x and y in main.
Arrays are a bit special. When you have a int[] as function parameter it means the same as int* (pointer to int). When you pass the array to the function you are actually passing a pointer to the first element in the array. What I said above about the function receiving a copy is still true but it is important to note that it is a copy of the pointer that is passed to the function (not a copy of the whole array). The pointer can then be used inside the function to modify the original array that was passed to the function.