Thuta Learning
ရှာဖွေရန်
IntermediateProgrammingbeginner

Functions

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

Function ဆိုတာ task တစ်ခုကို နာမည်ပေးပြီး သီးခြားခွဲရေးထားတဲ့ code block ပါ။ Code ကို ပြန်သုံးနိုင်စေတယ်၊ program ကို ဖတ်ရလွယ်စေတယ်၊ bug ရှာရလွယ်စေတယ်။ တစ်ခုခုကို တစ်ခါထက်ပိုလုပ်ရမယ်ဆိုရင် function ခွဲဖို့ စဉ်းစားပါ။

cpp
#include <iostream>
using namespace std;

void showWelcome() {
    cout << "Welcome to C++ lesson!" << endl;
}

int add(int a, int b) {
    return a + b;
}

int main() {
    showWelcome();
    int total = add(5, 3);
    cout << "Total: " << total;
    return 0;
}

showWelcome() က output ထုတ်ပေးပြီး return value မလိုလို့ void သုံးထားပါတယ်။ add() က integer နှစ်ခုယူပြီး result integer ပြန်ပေးလို့ return type ကို int ထားပါတယ်။

You should see
Welcome to C++ lesson! Total: 8

Info

Function name ကို အလုပ်ဘာလုပ်လဲ သိသာအောင်ပေးပါ။ doThing() ထက် calculateTotal() က နောက်မှပြန်ဖတ်တဲ့အခါ ပိုနားလည်လွယ်ပါတယ်။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Return type နဲ့ return value မကိုက်တာကို သတိထားပါ။ int function ဖြစ်ပြီး return မပြန်တာက warning/error ဖြစ်နိုင်ပါတယ်။
Functions | Thuta Learning