Kamis, 22 November 2012

FUNCTIONS






 Functions In C++

Using functions we can structure our programs in a more modular way, accessing all the potential that structured programming can offer to us in C++.
A function is a group of statements that is executed when it is called from some point of the program. The following is its format:

type name ( parameter1, parameter2, ...) { statements }

Where:
  •  Type is the data type specifier of the data returned by the function.
  • Name is the identifier by which it will be possible to call the function.
  • Parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas.
  • SStatements is the function's body. It is a block of statements surrounded by braces { }.


Here you have the first function example:

// function example
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}
The result is 8

In order to examine this code, first of all remember something said at the beginning of this tutorial: a C++
program always begins its execution by the main function. So we will begin there.

We can see how the main function begins by declaring the variable z of type int. Right after that, we see a call to a function called addition. Paying attention we will be able to see the similarity between the structure of the call to the function and the declaration of the function itself some code lines above:

 
Int addition ( int a, int b )
z  = addition ( 5 , 6 )

The parameters and arguments have a clear correspondence. Within the main function we called to addition passing two values: 5 and 3, that correspond to the int a and int b parameters declared for function addition.

At the point at which the function is called from within main, the control is lost by main and passed to function addition. The value of both arguments passed in the call (5 and 3) are copied to the local variables int a and int b within the function.

Function addition declares another local variable (int r), and by means of the expression r=a+b, it assigns to r the result of a plus b. Because the actual parameters passed for a and b are 5 and 3 respectively, the result is 8.

The following line of code:

return (r);


Finalizes function addition, and returns the control back to the function that called it in the first place (in this case, main). At this moment the program follows it regular course from the same point at which it was interrupted by the call to addition. But additionally, because the return statement in function addition specified a value: the content of variable r (return (r);), which at that moment had a value of 8.

Int addition  ( int a, int b)
Z – addition ( 5 , 3 );

So being the value returned by a function the value given to the function call itself when it is evaluated, the variable z will be set to the value returned by addition (5, 3), that is 8. To explain it another way, you can imagine that the call to a function (addition (5,3)) is literally replaced by the value it returns (8).

The following line of code in main is:

cout << "The result is " << z;

That, as you may already expect, produces the printing of the result on the screen.


Scope of variables

The scope of variables declared within a function or any other inner block is only their own function or their own block and cannot be used outside of them. For example, in the previous example it would have been impossible to use the variables a, b or r directly in function main since they were variables local to function addition. Also, it would have been impossible to use the variable z directly within function addition, since this was a variable local to the function main.


- Global Variables
- Local Variabels
- Intuctions

Therefore, the scope of local variables is limited to the same block level in which they are declared. Nevertheless, we also have the possibility to declare global variables; These are visible from any point of the code, inside and outside all functions. In order to declare global variables you simply have to declare the variable outside any function or block; that means, directly in the body of the program.

And here is another example about functions:

// function example
#include <iostream>
using namespace std;
int subtraction (int a, int b)
{
int r;
r=a-b;
return (r);
}
int main ()
{
int x=5, y=3, z;
z = subtraction (7,2);
cout << "The first result is " << z << '\n';
cout << "The second result is " << subtraction (7,2) << '\n';
cout << "The third result is " << subtraction (x,y) << '\n';
z= 4 + subtraction (x,y);
cout << "The fourth result is " << z << '\n';
return 0;
}
The first result is 5
The second result is 5
The third result is 2
The fourth result is 6

In this case we have created a function called subtraction. The only thing that this function does is to subtract both passed parameters and to return the result.

Nevertheless, if we examine function main we will see that we have made several calls to function subtraction.We have used some different calling methods so that you see other ways or moments when a function can be called.

In order to fully understand these examples you must consider once again that a call to a function could be replaced by the value that the function call itself is going to return. For example, the first case (that you should already know because it is the same pattern that we have used in previous examples):

z = subtraction (7,2);
cout << "The first result is " << z;

If we replace the function call by the value it returns (i.e., 5), we would have:

z = 5;
cout << "The first result is " << z;

As well as

cout << "The second result is " << subtraction (7,2);

has the same result as the previous call, but in this case we made the call to subtraction directly as an insertion parameter for cout. Simply consider that the result is the same as if we had written:

cout << "The second result is " << 5;

since 5 is the value returned by subtraction (7,2).

In the case of:

cout << "The third result is " << subtraction (x,y);

The only new thing that we introduced is that the parameters of subtraction are variables instead of constants. That is perfectly valid. In this case the values passed to function subtraction are the values of x and y, that are 5 and 3 respectively, giving 2 as result.

The fourth case is more of the same. Simply note that instead of:

z = 4 + subtraction (x,y);

we could have written:

z = subtraction (x,y) + 4;



With exactly the same result. I have switched places so you can see that the semicolon sign (;) goes at the end of the whole statement. It does not necessarily have to go right after the function call. The explanation might be once again that you imagine that a function can be replaced by its returned value:

z = 4 + 2;
z = 2 + 4;

Functions with no type. The use of void.

If you remember the syntax of a function declaration:

type name ( argument1, argument2 ...) statement

You will see that the declaration begins with a type, that is the type of the function itself (i.e., the type of the datum that will be returned by the function with the return statement). But what if we want to return no value?

Imagine that we want to make a function just to show a message on the screen. We do not need it to return any value. In this case we should use the void type specifier for the function. This is a special specifier that indicates absence of  type.

// void function example
#include <iostream>
using namespace std;
void printmessage ()
{
cout << "I'm a function!";
}
int main ()
{
printmessage ();
return 0;
}
I'm a function!

 
Void can also be used in the function's parameter list to explicitly specify that we want the function to take no actual parameters when it is called. For example, function printmessage could have been declared as:

void printmessage (void)
{
cout << "I'm a function!";
}

Although it is optional to specify void in the parameter list. In C++, a parameter list can simply be left blank if we want a function with no parameters.
What you must always remember is that the format for calling a function includes specifying its name and
enclosing its parameters between parentheses. The non-existence of parameters does not exempt us from the obligation to write the parentheses. For that reason the call to printmessage is:

printmessage ();

The parentheses clearly indicate that this is a call to a function and not the name of a variable or some other C++ statement. The following call would have been incorrect:

printmessage;


Fungsi Di dalam C++

Menggunakan fungsi kita dapat menyusun program kami dengan cara yang lebih modular, mengakses semua potensi yang pemrograman terstruktur dapat menawarkan kepada kita dalam C + +.

Fungsi adalah sekelompok pernyataan yang dieksekusi ketika dipanggil dari beberapa titik program. Berikut ini adalah format:
ketik nama (paramater1, parameter2, ...) {pernyataan}

Di mana:
  • Tipe-tipe data specifier dari data yang dikembalikan oleh fungsi
  • Nama adalah identifier dimana akan mungkin untuk memanggil fungsi. 
  • Parameter (sebanyak yang diperlukan): Setiap argumen terdiri dari tipe data specifier diikuti oleh identifier, seperti deklarasi variabel reguler (misalnya: int x) dan yang bertindak dalam fungsi sebagai variabel lokal biasa. Mereka memungkinkan untuk melewati argumen untuk fungsi ketika dipanggil. Parameter yang berbeda dipisahkan dengan koma. 
  • Pernyataan adalah tubuh fungsi itu. Ini adalah blok statemen dikelilingi oleh kawat gigi {}.    
Di sini Anda memiliki contoh fungsi pertama:

// function example
#include <iostream>
using namespace std;
int addition ( int a, int b)
{
int r;
r=a+b;
return (r);
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}
Hasilnya adalah 8 


Dalam rangka untuk memeriksa kode ini, pertama-tama ingat sesuatu yang dikatakan di awal tutorial ini: C + + program selalu dimulai pelaksanaannya oleh fungsi utama. Jadi kita akan mulai di sana.

Kita bisa melihat bagaimana fungsi
utama dimulai dengan mendeklarasikan z variabel bertipe int. Tepat setelah itu, kita melihat panggilan ke fungsi disebut penambahan. Memperhatikan kita akan dapat melihat kesamaan antara struktur panggilan ke fungsi dan deklarasi fungsi itu sendiri baris beberapa kode di atas:

Int addition ( int a, int b )
z  = addition ( 5 , 6 )

Parameter dan argumen memiliki korespondensi yang jelas. Dalam fungsi utama kita dipanggil untuk penambahan melewati dua nilai: 5 dan 3, yang sesuai dengan suatu int dan int b parameter dideklarasikan untuk penambahan fungsi.

Pada titik di mana fungsi ini dipanggil dari dalam
utama, kontrol hilang oleh utama dan diteruskan ke fungsi penambahan. Nilai kedua argumen lulus dalam panggilan (5 dan 3) akan disalin ke variabel lokal int a dan b int dalam fungsi.

Selain itu fungsi lain menyatakan variabel lokal (int r), dan melalui ekspresi  r = a + b, akan menetapkan ke r hasil dari b ditambah. Karena parameter aktual berlalu bagi a dan b adalah 5 dan 3 masing-masing, hasilnya adalah 8.

Baris kode berikut:

return (r);

Finalizes Selain fungsi, dan mengembalikan kembali kontrol untuk fungsi yang memanggilnya di tempat pertama (dalam hal ini, utama). Pada saat ini program mengikuti kursus reguler dari titik yang sama di mana ia terganggu oleh panggilan untuk penambahan. Tapi tambahan, karena pernyataan kembali di samping fungsi ditentukan nilai: isi variabel r (return (r);), yang pada saat itu memiliki nilai 8. Nilai ini menjadi nilai mengevaluasi fungsi panggil.

Int addition  ( int a, int b)
Z – addition ( 5 , 3 );

Jadi menjadi nilai yang dikembalikan oleh fungsi nilai yang diberikan ke fungsi panggilan itu sendiri ketika dievaluasi, z variabel akan diatur ke nilai yang dikembalikan oleh penambahan (5, 3), yaitu 8. Untuk menjelaskannya dengan cara lain, Anda dapat membayangkan bahwa panggilan ke fungsi (selain (5,3)) secara harfiah digantikan oleh nilai itu kembali (8).

Baris kode berikut di utama adalah:
cout << "The result is " << z;
Itu, karena Anda mungkin sudah berharap, menghasilkan pencetakan hasil di layar.

Lingkup variabel

Ruang lingkup variabel yang dideklarasikan dalam fungsi atau blok batin lainnya hanya fungsi mereka sendiri atau blok mereka sendiri dan tidak dapat digunakan di luar dari mereka. Misalnya, dalam contoh sebelumnya itu akan menjadi mustahil untuk menggunakan variabel a, b atau r secara langsung dalam fungsi utama karena mereka adalah variabel lokal untuk penambahan fungsi. Juga, itu akan menjadi mungkin untuk menggunakan variabel z langsung dalam penambahan fungsi, karena ini adalah variabel lokal untuk fungsi utama.

 
- Global Variables
- Local Variabels
- Intuctions

Oleh karena itu, ruang lingkup variabel lokal terbatas pada tingkat blok yang sama di mana mereka dinyatakan. Namun demikian, kami juga memiliki kemungkinan untuk mendeklarasikan variabel global, ini terlihat dari setiap titik kode, di dalam dan di luar semua fungsi. Dalam rangka untuk mendeklarasikan variabel global Anda hanya perlu mendeklarasikan variabel di luar fungsi atau blok, yang berarti, langsung di tubuh program.
Dan di sini adalah contoh lain tentang fungsi:
// function example
#include <iostream>
using namespace std;
int subtraction (int a, int b)
{
int r;
r=a-b;
return (r);
}
int main ()
{
int x=5, y=3, z;
z = subtraction (7,2);
cout << "The first result is " << z << '\n';
cout << "The second result is " << subtraction (7,2) << '\n';
cout << "The third result is " << subtraction (x,y) << '\n';
z= 4 + subtraction (x,y);
cout << "The fourth result is " << z << '\n';
return 0;
}
The first result is 5
The second result is 5
The third result is 2
The fourth result is 6
Dalam hal ini kami telah membuat sebuah fungsi yang disebut pengurangan. Satu-satunya hal yang dilakukan adalah fungsi ini untuk mengurangi kedua parameter berlalu dan kembali hasilnya.

Namun demikian, jika kita meneliti fungsi
utama kita akan melihat bahwa kami telah membuat beberapa panggilan berfungsi pengurangan. Kami telah menggunakan beberapa metode yang berbeda menelepon sehingga Anda melihat cara lain atau saat-saat ketika fungsi dapat dipanggil.

Dalam rangka untuk memahami contoh-contoh ini Anda harus mempertimbangkan sekali lagi bahwa panggilan ke fungsi bisa diganti dengan nilai yang panggilan fungsi itu sendiri akan kembali. Misalnya, kasus pertama (bahwa Anda sudah harus tahu karena itu adalah pola yang sama yang kita telah digunakan dalam contoh sebelumnya):

Jika Kita mengganti fungsi panggilan dengan nilai itu kembali (yaitu,5) kita akan memilki;
 
z = 5; cout << "The first result is " << z;
 
Maupun 
 
cout << "The second result is " << subtraction (7,2);
 
 
Memiliki hasil yang sama dengan panggilan sebelumnya, tetapi dalam kasus ini kami membuat 
panggilan untuk pengurangan secara langsung sebagai parameter penyisipan untuk pengadilan. 
Cukup menganggap bahwa hasilnya adalah sama seperti jika kita telah menulis: 

cout << "The second result is " << 5;
 
Sejak 5 adalah nilai yang dikembalikan oleh pengurangan (7,2). 

Dalam hal: 


cout << "The third result is " << subtraction (x,y); 

Satu-satunya hal baru yang kita diperkenalkan adalah bahwa parameter pengurangan adalah 
variabel bukan konstanta. Itu benar-benar berlaku. Dalam hal ini nilai yang dikirimkan berfungsi
pengurangan adalah nilai-nilai x dan y, yang 5 dan 3 masing-masing, memberikan 2 sebagai hasilnya.

Kasus keempat adalah lebih sama. Cukup perhatikan bahwa bukan:
 
 z = 4 + subtraction (x,y);
 
Kita bisa menulis: 
 
z = subtraction (x,y) + 4; 
 
Dengan hasil yang sama persis. Saya telah beralih tempat sehingga Anda dapat melihat bahwa 
tanda titik  koma (;) pergi pada akhir pernyataan keseluruhan. Ini tidak selalu harus pergi tepat
setelah fungsi panggil. Penjelasannya mungkin sekali lagi bahwa Anda membayangkan bahwa
fungsi dapat digantikan oleh nilainya dikembalikan:  
 
z = 4 + 2; z = 2 + 4;  


Fungsi dengan tipe no. Penggunaan batal.

Jika Anda ingat sintaks dari sebuah deklarasi fungsi:

Ketik nama (argument1, argument2 ...) pernyataan

Anda akan melihat bahwa deklarasi dimulai dengan tipe, yaitu tipe dari fungsi itu sendiri (yaitu, jenis datum yang akan dikembalikan oleh fungsi dengan pernyataan kembali). Tapi bagaimana kalau kita 
ingin mengembalikan nilai tidak?

Bayangkan bahwa kita ingin membuat fungsi hanya untuk menampilkan pesan di layar. Kita tidak perlu untuk mengembalikan nilai apapun. Dalam hal ini kita harus menggunakan specifier tipe void untuk fungsi. Ini adalah specifier khusus yang menunjukkan adanya jenis.
 
// void function example 
#include <iostream> 
using namespace std;
 
void printmessage ()
{
cout << "I'm a function!" ;
}
int main ()
{ 
printmessage ();
return 0;
}
Aku fungsi!



Batal juga dapat digunakan dalam daftar parameter fungsi untuk secara eksplisit menentukan bahwa 
kita ingin fungsi untuk tidak mengambil parameter yang sebenarnya ketika itu disebut. Misalnya, fungsi
printmessage  bisa saja dinyatakan sebagai:
 
void printmessage ( void ) { cout << "I'm a function!" ; }
 
Walaupun ini merupakan opsional untuk menentukan kekosongan dalam daftar parameter. Dalam C + +, 
sebuah daftar parameter hanya dapat dibiarkan kosong jika kita ingin fungsi tanpa parameter. 


Apa yang Anda harus selalu diingat adalah bahwa format untuk memanggil fungsi termasuk
menentukan nama dan melampirkan parameter antara kurung. Non-keberadaan parameter tidak 
membebaskan kita dari kewajiban  untuk menulis tanda kurung. Untuk alasan bahwa panggilan untuk
printmessage adalah:
 
printmessage (); 
 
Tanda kurung jelas menunjukkan bahwa ini adalah panggilan ke fungsi dan bukan nama variabel atau beberapa lainnya C + + pernyataan. Panggilan berikut akan menjadi salah:

printmessage; 
 
.... 















0 komentar:

Posting Komentar