Posts Subscribe comment Comments

Variabel C++

Manfaat dari "Hello World" program ditunjukkan pada bagian sebelumnya cukup dipertanyakan. We had to write several lines of code, compile them, and then execute the resulting program just to obtain a simple sentence written on the screen as result. Kami harus menulis beberapa baris kode, kompilasi mereka, dan kemudian jalankan program yang dihasilkan hanya untuk mendapatkan sebuah kalimat sederhana yang ditulis pada layar sebagai hasilnya. It certainly would have been much faster to type the output sentence by ourselves. Hal ini tentu akan lebih cepat untuk jenis kalimat output dengan diri kita sendiri. However, programming is not limited only to printing simple texts on the screen. Namun, program ini tidak terbatas hanya pada teks-teks sederhana mencetak pada layar. In order to go a little further on and to become able to write programs that perform useful tasks that really save us work we need to introduce the concept of variable . Dalam rangka untuk pergi sedikit lebih lanjut dan untuk menjadi mampu menulis program yang melakukan tugas-tugas yang berguna yang benar-benar menyelamatkan kita bekerja kita perlu memperkenalkan konsep variabel.

Let us think that I ask you to retain the number 5 in your mental memory, and then I ask you to memorize also the number 2 at the same time. Mari kita berpikir bahwa saya meminta Anda untuk mempertahankan nomor 5 di memori mental Anda, dan kemudian saya meminta Anda untuk menghafal juga nomor 2 pada waktu yang sama. You have just stored two different values in your memory. Anda baru saja disimpan dua nilai yang berbeda di memori Anda. Now, if I ask you to add 1 to the first number I said, you should be retaining the numbers 6 (that is 5+1) and 2 in your memory. Sekarang, jika saya meminta Anda untuk menambahkan 1 ke nomor pertama yang saya bilang, Anda harus mempertahankan nomor 6 (yang adalah 5 +1) dan 2 dalam memori Anda. Values that we could now for example subtract and obtain 4 as result. Nilai-nilai yang kita sekarang bisa misalnya mengurangi dan memperoleh 4 sebagai hasilnya.

The whole process that you have just done with your mental memory is a simile of what a computer can do with two variables. Seluruh proses yang baru saja Anda lakukan dengan memori mental Anda adalah simile dari apa komputer dapat dilakukan dengan dua variabel. The same process can be expressed in C++ with the following instruction set: Proses yang sama dapat diekspresikan dalam C + + dengan set instruksi berikut:

1 1
2 2
3 3
4 4
a = 5; b = 2; a = a + 1; result = a - b; 


Obviously, this is a very simple example since we have only used two small integer values, but consider that your computer can store millions of numbers like these at the same time and conduct sophisticated mathematical operations with them. Jelas, ini adalah contoh yang sangat sederhana karena kita hanya menggunakan dua nilai integer yang kecil, namun pertimbangkan bahwa komputer Anda dapat menyimpan jutaan angka seperti ini pada waktu yang sama dan melakukan operasi matematika canggih dengan mereka.

Therefore, we can define a variable as a portion of memory to store a determined value. Oleh karena itu, kita dapat mendefinisikan sebuah variabel sebagai bagian dari memori untuk menyimpan nilai yang telah ditentukan.

Each variable needs an identifier that distinguishes it from the others. Setiap variabel membutuhkan identifier yang membedakannya dari yang lain. For example, in the previous code the variable identifiers were a , b and result , but we could have called the variables any names we wanted to invent, as long as they were valid identifiers. Sebagai contoh, dalam kode sebelumnya pengenal variabel adalah a , b dan result , tapi kita bisa disebut variabel nama-nama kita ingin menemukan, selama mereka pengidentifikasi valid.

Identifiers Pengidentifikasi

A valid identifier is a sequence of one or more letters, digits or underscore characters ( _ ). A valid identifier adalah urutan dari satu atau lebih huruf, angka atau karakter garis bawah ( _ ). Neither spaces nor punctuation marks or symbols can be part of an identifier. Baik ruang maupun tanda baca atau simbol dapat menjadi bagian dari sebuah identifier. Only letters, digits and single underscore characters are valid. Hanya huruf, angka dan karakter garis bawah tunggal berlaku. In addition, variable identifiers always have to begin with a letter. Selain itu, identifier variabel harus selalu diawali dengan huruf. They can also begin with an underline character ( _ ), but in some cases these may be reserved for compiler specific keywords or external identifiers, as well as identifiers containing two successive underscore characters anywhere. Mereka juga dapat dimulai dengan sebuah karakter garis bawah ( _ ), namun dalam beberapa kasus ini mungkin disediakan untuk kata kunci spesifik compiler atau pengidentifikasi eksternal, serta pengidentifikasi mengandung dua karakter underscore berturut-turut di mana saja. In no case can they begin with a digit. Dalam hal tidak ada yang bisa mereka mulai dengan angka.

Another rule that you have to consider when inventing your own identifiers is that they cannot match any keyword of the C++ language nor your compiler's specific ones, which are reserved keywords . Lain aturan bahwa Anda harus dipertimbangkan ketika menciptakan pengidentifikasi sendiri adalah bahwa mereka tidak bisa cocok dengan kata kunci dari C + + bahasa yang tidak spesifik's compiler anda, yang dilindungi kata kunci. The standard reserved keywords are: Kata kunci reserved standar adalah:


asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while


Additionally, alternative representations for some operators cannot be used as identifiers since they are reserved words under some circumstances: Selain itu, representasi alternatif untuk beberapa operator tidak dapat digunakan sebagai identifier karena mereka dilindungi kata-kata di bawah beberapa kondisi:


and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq


Your compiler may also include some additional specific reserved keywords. compiler Anda juga mungkin mencakup beberapa kata kunci tambahan reserved tertentu.

Very important: The C++ language is a "case sensitive" language. Sangat penting: C + + bahasa adalah "case sensitive" bahasa. That means that an identifier written in capital letters is not equivalent to another one with the same name but written in small letters. Itu berarti bahwa identifier ditulis dalam huruf kapital yang tidak setara dengan yang lain dengan nama yang sama tapi ditulis dalam huruf kecil. Thus, for example, the RESULT variable is not the same as the result variable or the Result variable. Jadi, misalnya, RESULT variabel tidak sama dengan result variabel atau Result variabel. These are three different variable identifiers. Ini adalah tiga identifier variabel yang berbeda.

Fundamental data types Fundamental tipe data

When programming, we store the variables in our computer's memory, but the computer has to know what kind of data we want to store in them, since it is not going to occupy the same amount of memory to store a simple number than to store a single letter or a large number, and they are not going to be interpreted the same way. Ketika program, kita menyimpan variabel dalam memori komputer kita, tetapi komputer harus mengetahui jenis data yang kita inginkan untuk menyimpan di dalamnya, karena itu tidak akan menduduki jumlah yang sama dari memori untuk menyimpan nomor sederhana daripada untuk menyimpan huruf tunggal atau nomor besar, dan mereka tidak akan diinterpretasikan dengan cara yang sama.

The memory in our computers is organized in bytes. Memori dalam komputer kita diatur dalam byte. A byte is the minimum amount of memory that we can manage in C++. byte adalah jumlah minimum memori yang kita dapat mengatur di C + +. A byte can store a relatively small amount of data: one single character or a small integer (generally an integer between 0 and 255). byte dapat menyimpan jumlah yang relatif kecil data: satu karakter tunggal atau sebuah integer kecil (umumnya merupakan integer antara 0 dan 255). In addition, the computer can manipulate more complex data types that come from grouping several bytes, such as long numbers or non-integer numbers. Selain itu, komputer dapat memanipulasi tipe data yang lebih kompleks yang berasal dari pengelompokan beberapa byte, seperti nomor panjang atau nomor non-integer.

Next you have a summary of the basic fundamental data types in C++, as well as the range of values that can be represented with each one: Berikutnya Anda memiliki ringkasan dari tipe data dasar fundamental dalam C + +, serta rentang nilai yang dapat diwakili dengan masing-masing:

Name Nama Description Deskripsi Size* Ukuran * Range* Range *
char Character or small integer. Karakter atau integer kecil. 1byte 1byte signed: -128 to 127 ditandatangani: -128 sampai 127
unsigned: 0 to 255 unsigned: 0 sampai 255
short int
( short ) ( short )
Short Integer. Short Integer. 2bytes 2bytes signed: -32768 to 32767 ditandatangani: -32.768-32.767
unsigned: 0 to 65535 unsigned: 0-65535
int Integer. Integer. 4bytes 4bytes signed: -2147483648 to 2147483647 ditandatangani: -2147483648 ke 2147483647
unsigned: 0 to 4294967295 unsigned: 0-4294967295
long int
( long ) ( long )
Long integer. Long integer. 4bytes 4bytes signed: -2147483648 to 2147483647 ditandatangani: -2147483648 ke 2147483647
unsigned: 0 to 4294967295 unsigned: 0-4294967295
bool Boolean value. Nilai Boolean. It can take one of two values: true or false. Hal ini dapat mengambil salah satu dari dua nilai: true atau false. 1byte 1byte true or false true atau false
float Floating point number. Floating titik nomor. 4bytes 4bytes +/- 3.4e +/- 38 (~7 digits) + / - 3.4e + / - 38 (~ 7 digit)
double Double precision floating point number. Double presisi floating point nomor. 8bytes 8bytes +/- 1.7e +/- 308 (~15 digits) + / - 1.7e + / - 308 (~ 15 digit)
long double Long double precision floating point number. Long double precision floating point nomor. 8bytes 8bytes +/- 1.7e +/- 308 (~15 digits) + / - 1.7e + / - 308 (~ 15 digit)
wchar_t Wide character. Lebar karakter. 2 or 4 bytes 2 atau 4 bytes 1 wide character 1 karakter lebar


* The values of the columns Size and Range depend on the system the program is compiled for. * Nilai dari Ukuran kolom dan Range tergantung pada sistem program ini dikompilasi untuk. The values shown above are those found on most 32-bit systems. Nilai-nilai yang ditunjukkan di atas adalah yang ditemukan pada sistem 32-bit yang paling. But for other systems, the general specification is that int has the natural size suggested by the system architecture (one "word" ) and the four integer types char , short , int and long must each one be at least as large as the one preceding it, with char being always one byte in size. Tetapi untuk sistem lain, spesifikasi umumnya adalah bahwa int memiliki ukuran alami disarankan oleh arsitektur sistem (satu "kata") dan empat tipe integer char , short , int dan long masing-masing harus setidaknya sama besar dengan yang sebelumnya itu, dengan char yang selalu merupakan satu byte dalam ukuran. The same applies to the floating point types float , double and long double , where each one must provide at least as much precision as the preceding one. Hal yang sama berlaku untuk floating point jenis float , double dan long double , di mana masing-masing harus menyediakan setidaknya presisi sebanyak yang sebelumnya.

Declaration of variables Deklarasi variabel

In order to use a variable in C++, we must first declare it specifying which data type we want it to be. Untuk menggunakan variabel di C + +, pertama kita harus mendeklarasikan tipe data menetapkan yang kita inginkan. The syntax to declare a new variable is to write the specifier of the desired data type (like int, bool, float...) followed by a valid variable identifier. Sintaks untuk mendeklarasikan variabel baru untuk menulis specifier tipe data yang diinginkan (seperti int, bool, float ...) diikuti oleh variabel identifier yang valid. For example: Sebagai contoh:

1 1
2 2
int a; float mynumber; 


These are two valid declarations of variables. Ini adalah dua deklarasi variabel yang valid. The first one declares a variable of type int with the identifier a . Yang pertama mendeklarasikan variabel bertipe int dengan sebuah identifier. The second one declares a variable of type float with the identifier mynumber . Yang kedua menyatakan sebuah variabel tipe float dengan identifier Angkanya. Once declared, the variables a and mynumber can be used within the rest of their scope in the program. Setelah menyatakan, variabel dan Angkanya dapat digunakan dalam sisa lingkup mereka dalam program.

If you are going to declare more than one variable of the same type, you can declare all of them in a single statement by separating their identifiers with commas. Jika Anda akan menyatakan lebih dari satu variabel dari jenis yang sama, Anda dapat mendeklarasikan semua dari mereka dalam sebuah pernyataan tunggal dengan memisahkan identifier mereka dengan koma. For example: Sebagai contoh:

 
int a, b, c; 


This declares three variables ( a , b and c ), all of them of type int , and has exactly the same meaning as: Ini mendeklarasikan tiga variabel (a, b, dan c), semuanya bertipe int, dan memiliki arti yang sama persis sebagai:

1 1
2 2
3 3
int a; int b; int c; 


The integer data types char , short , long and int can be either signed or unsigned depending on the range of numbers needed to be represented. Jenis data integer char, pendek, panjang dan int dapat berupa signed atau unsigned tergantung pada kisaran angka yang dibutuhkan untuk diwakili. Signed types can represent both positive and negative values, whereas unsigned types can only represent positive values (and zero). Signed jenis dapat mewakili kedua nilai-nilai positif dan negatif, sedangkan tipe unsigned hanya dapat mewakili nilai-nilai positif (dan nol). This can be specified by using either the specifier signed or the specifier unsigned before the type name. Hal ini dapat ditentukan dengan menggunakan salah satu specifier menandatangani atau specifier unsigned sebelum nama jenis. For example: Sebagai contoh:

1 1
2 2
unsigned short int NumberOfSisters; signed int MyAccountBalance; 


By default, if we do not specify either signed or unsigned most compiler settings will assume the type to be signed, therefore instead of the second declaration above we could have written: Secara default, jika kita tidak menentukan baik ditandatangani atau unsigned pengaturan compiler kebanyakan akan menganggap tipe yang akan ditandatangani, sehingga bukan deklarasi kedua di atas kita bisa menulis:

 
int MyAccountBalance; 


with exactly the same meaning (with or without the keyword signed ) dengan persis arti yang sama (dengan atau tanpa kata kunci signed )

An exception to this general rule is the char type, which exists by itself and is considered a different fundamental data type from signed char and unsigned char , thought to store characters. Pengecualian untuk peraturan umum adalah tipe char, yang ada dengan sendirinya dan dianggap sebagai data mendasar tipe berbeda dari ditandatangani char dan unsigned char, pemikiran untuk menyimpan karakter. You should use either signed or unsigned if you intend to store numerical values in a char -sized variable. Anda harus menggunakan baik signed atau unsigned jika Anda berniat untuk menyimpan nilai numerik dalam berukuran variabel char.

short and long can be used alone as type specifiers. short dan long dapat digunakan sendiri sebagai specifier jenis. In this case, they refer to their respective integer fundamental types: short is equivalent to short int and long is equivalent to long int . Dalam hal ini, mereka lihat integer masing jenis fundamental mereka: short sama dengan short int dan long setara dengan long int . The following two variable declarations are equivalent: Dua berikut deklarasi variabel adalah setara:

1 1
2 2
short Year; short int Year; 


Finally, signed and unsigned may also be used as standalone type specifiers, meaning the same as signed int and unsigned int respectively. Akhirnya, signed dan unsigned juga dapat digunakan sebagai specifier jenis mandiri, yang berarti sama dengan signed int dan unsigned int masing-masing. The following two declarations are equivalent: Dua berikut deklarasi yang setara:

1 1
2 2
unsigned NextYear; unsigned int NextYear; 


To see what variable declarations look like in action within a program, we are going to see the C++ code of the example about your mental memory proposed at the beginning of this section: Untuk melihat apa deklarasi variabel terlihat seperti dalam aksi di dalam sebuah program, kita akan melihat C + + kode contoh tentang memori mental Anda yang diusulkan di awal bagian ini:

1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 11
12 12
13 13
14 14
15 15
16 16
17 17
18 18
19 19
20 20
21 21
22 22
23 23
// operating with variables #include  using namespace std; int main () { // declaring variables: int a, b; int result; // process: a = 5; b = 2; a = a + 1; result = a - b; // print out the result: cout << result; // terminate the program: return 0; } 
4 4 


Do not worry if something else than the variable declarations themselves looks a bit strange to you. Jangan khawatir jika sesuatu yang lain daripada deklarasi variabel sendiri terlihat sedikit aneh bagi Anda. You will see the rest in detail in coming sections. Anda akan melihat sisa secara rinci pada bagian mendatang.

Scope of variables Lingkup variabel

All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous code at the beginning of the body of the function main when we declared that a , b , and result were of type int . Semua variabel yang kami bermaksud untuk digunakan dalam program harus telah dinyatakan dengan specifier jenisnya dalam titik sebelumnya dalam kode, seperti yang kami lakukan dalam kode sebelumnya pada awal tubuh fungsi utama ketika kita menyatakan bahwa, b, dan hasil adalah tipe int.

A variable can be either of global or local scope. Sebuah variabel dapat menjadi salah satu dari lingkup global atau lokal. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block. Sebuah variabel global adalah variabel dideklarasikan dalam tubuh utama dari kode sumber, di luar semua fungsi, sementara variabel lokal merupakan salah satu dideklarasikan dalam tubuh fungsi atau blok.



Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration. Variabel global dapat dirujuk dari mana saja di kode, bahkan di dalam fungsi, setiap kali setelah deklarasi.

The scope of local variables is limited to the block enclosed in braces ( {} ) where they are declared. Ruang lingkup variabel lokal terbatas blok diapit oleh kurung ( {} ) dimana mereka dinyatakan. For example, if they are declared at the beginning of the body of a function (like in function main ) their scope is between its declaration point and the end of that function. Sebagai contoh, jika mereka dinyatakan pada awal tubuh fungsi (seperti dalam fungsi utama) ruang lingkup mereka adalah antara titik deklarasi dan akhir fungsi itu. In the example above, this means that if another function existed in addition to main , the local variables declared in main could not be accessed from the other function and vice versa. Dalam contoh di atas, ini berarti bahwa jika ada fungsi lain selain utama, variabel lokal dideklarasikan dalam main tidak bisa diakses dari fungsi lainnya dan sebaliknya.

Initialization of variables Inisialisasi variabel

When declaring a regular local variable, its value is by default undetermined. Ketika mendeklarasikan variabel lokal biasa, nilainya secara default belum ditentukan. But you may want a variable to store a concrete value at the same moment that it is declared. Tapi Anda mungkin ingin variabel untuk menyimpan nilai beton pada saat yang sama yang dideklarasikan. In order to do that, you can initialize the variable. Untuk melakukan itu, Anda bisa menginisialisasi variabel. There are two ways to do this in C++: Ada dua cara untuk melakukan ini di C + +:

The first one, known as c-like initialization , is done by appending an equal sign followed by the value to which the variable will be initialized: Yang pertama, yang dikenal sebagai seperti inisialisasi c, dilakukan dengan menambahkan tanda yang sama diikuti dengan nilai variabel yang akan diinisialisasi:

type identifier = initial_value ;

For example, if we want to declare an int variable called a initialized with a value of 0 at the moment in which it is declared, we could write: Sebagai contoh, jika kita ingin mendeklarasikan variabel int disebut diinisialisasi dengan nilai 0 pada saat di mana dinyatakan, kita bisa menulis:

 
int a = 0; 


The other way to initialize variables, known as constructor initialization , is done by enclosing the initial value between parentheses ( () ): Cara lain untuk menginisialisasi variabel, yang dikenal sebagai inisialisasi konstruktor, dilakukan dengan melampirkan nilai awal antara tanda kurung ( () ):

type identifier (initial_value) ;

For example: Sebagai contoh:

 
int a (0); 


Both ways of initializing variables are valid and equivalent in C++. Kedua cara menginisialisasi variabel berlaku dan setara di C + +.

1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 11
12 12
13 13
14 14
15 15
16 16
17 17
// initialization of variables #include  using namespace std; int main () { int a=5; // initial value = 5 int b(2); // initial value = 2 int result; // initial value undetermined a = a + 3; result = a - b; cout << result; return 0; } 
6 6 


Introduction to strings Pengantar string

Variables that can store non-numerical values that are longer than one single character are known as strings. Variabel yang dapat menyimpan nilai non-numerik yang lebih panjang dari satu karakter tunggal yang dikenal sebagai string.

The C++ language library provides support for strings through the standard string class. C + + perpustakaan bahasa menyediakan dukungan untuk string melalui standar string kelas. This is not a fundamental type, but it behaves in a similar way as fundamental types do in its most basic usage. Ini bukan tipe mendasar, tapi berperilaku dengan cara yang sama sebagai jenis fundamental lakukan dalam penggunaan yang paling dasar.

A first difference with fundamental data types is that in order to declare and use objects (variables) of this type we need to include an additional header file in our source code: and have access to the std namespace (which we already had in all our previous programs thanks to the using namespace statement). Perbedaan pertama dengan tipe data yang mendasar adalah bahwa untuk menyatakan dan menggunakan objek (variabel) tipe ini kita perlu menyertakan file header tambahan dalam kode sumber kami: dan memiliki akses ke std namespace (yang kita sudah dalam semua program sebelumnya terima kasih kepada using namespace pernyataan).

1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 11
// my first string #include  #include  using namespace std; int main () { string mystring = "This is a string" ; cout << mystring; return 0; } 
This is a string Ini adalah string 


As you may see in the previous example, strings can be initialized with any valid string literal just like numerical type variables can be initialized to any valid numerical literal. Seperti yang Anda lihat pada contoh sebelumnya, string dapat diinisialisasi dengan string literal yang valid seperti tipe variabel numerik dapat diinisialisasi untuk setiap berlaku numerik literal. Both initialization formats are valid with strings: Kedua format inisialisasi berlaku dengan string:

1 1
2 2
string mystring = "This is a string" ; string mystring ( "This is a string" ); 


Strings can also perform all the other basic operations that fundamental data types can, like being declared without an initial value and being assigned values during execution: String juga dapat melakukan semua operasi dasar lain yang mendasar tipe data bisa, seperti yang dideklarasikan tanpa nilai awal dan nilai-nilai yang diberikan selama eksekusi:

1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 11
12 12
13 13
14 14
15 15
// my first string #include  #include  using namespace std; int main () { string mystring; mystring = "This is the initial string content" ; cout << mystring << endl; mystring = "This is a different string content" ; cout << mystring << endl; return 0; } 
This is the initial string content Ini adalah konten string awal 
 This is a different string content Ini adalah konten string berbeda 


For more details on C++ strings, you can have a look at the string class reference . Untuk rincian lebih lanjut tentang string C + +, Anda dapat melihat pada referensi kelas string .

0

Silahkan Tulis Komentar Anda ...

Tunjukan apa yang kau harapkan................
komentar anda sangat berharga bagi kami

Related Posts Plugin for WordPress, Blogger...