Tutorial dan Contoh Return by Reference Pemrograman C++

Tutorial dan Contoh Return by Reference Pemrograman C++

Selamat datang kembali di TeknoTips.NET. TeknoTips.NET adalah media online Indonesia yang diluncurkan pada bulan Maret 2015. Kami berkomitmen menyajikan konten seputar teknologi yang berkualitas dan bermanfaat. Ulasan kami terdiri dari berbagai topik: pemrograman komputer & database, review produk, tutorial windows, linux, android, kumpulan source code & project program, referensi tugas akhir & skripsi, download ebook, game & software.

Pada kesempatan ini kita akan mengulas artikel yang berjudul : Tutorial dan Contoh Return by Reference Pemrograman C++.

In C++ Programming, you can pass values by reference but also you can return a value by reference.  To understand this feature, you should have knowledge of global variables. If a variable is defined outside every function, then that variable is called a global variable. Any part of program after global variable declaration can access global variable. Learn more about global variables. Consider this example:
C++ Functions, C++ Function Types, C++ Function Overloading, C++ Default Argument, C++ Storage Class, C++ Recursion, C++ Return Reference

Example 1: Return by Reference

#include <iostream>
using namespace std;
int n;
int& test();
int main() {
    test() = 5;
    cout<<n;
    return 0;
}
int& test() {
    return n;
}
Output
5
Explanation
In program above, the return type of function test() is int&. Hence this function returns by reference. The return statement is return n; but unlike return by value. This statement doesn't return value of n, instead it returns variable n itself.
Then the variable n is assigned to the left side of code test() = 5; and value of n is displayed.

Important Things to Care While Returning by Reference.

int& test() { 
    int n = 2; 
    return n; 
}
  • Ordinary function returns value but this function doesn't. Hence, you can't return constant from this function.
    int& test() {
        return 2;
    }
  • You can't return a local variable from this function.
Tag : C++ Functions, C++ Function Types, C++ Function Overloading, C++ Default Argument, C++ Storage Class, C++ Recursion, C++ Return Reference
Untuk mendapat notifikasi setiap artikel terbaru, masukkan e-mail anda disini
Selanjutnya cek e-mail anda untuk verifikasi.

Silahkan tuliskan komentar relevan Anda dengan jelas dan sopan, sesuai dengan topik postingan tentang ", " pada halaman dibawah ini.

0 Response to "Tutorial dan Contoh Return by Reference Pemrograman C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2


Iklan Bawah Artikel