iT邦幫忙

2021 iThome 鐵人賽

DAY 21
0
自我挑戰組

腦力激盪C++系列 第 21

[Day-21] 呼叫自訂函式(二)

上次練習了基本的函式語法
今天要接續著練習
我上次宣告的函式是int型態的
所以不管怎樣都會回傳值給主程式(假設主程式有呼叫此函式)
下面示範如果函式沒有回傳一個值,如→return x;
會發生什麼事呢?
/images/emoticon/emoticon06.gif

#include <iostream>
using namespace std;

int test(int x){
    x=x*10;
}

int main(void){
	int test_x;
	test_x = test(6);
	cout << test_x;
}

執行結果:

4745728
--------------------------------
Process exited after 0.08787 seconds with return value 0
請按任意鍵繼續...

那要如何設定不用回傳值
但也可以執行函式呢?

其實只要再宣告的時候
打上void就可以
舉例來說

#include <iostream>
using namespace std;

void test(){
	int x=6;
    x=x*10;
    cout << x ; 
}

int main(void){
	test();
}

執行結果:

60
--------------------------------
Process exited after 0.08787 seconds with return value 0
請按任意鍵繼續...

以上就是函式以及函式的回傳值練習啦~

那這邊我原本有個疑問
因為主程式的部分
其實也可以做到函式的功能
為什麼還需要函式呢?
/images/emoticon/emoticon19.gif
目前看起來就是讓程式碼看起來不會太雜亂
將原本在主程式的程式
分割成一個一個的函式
就可以清楚的知道
這個部分的程式碼在做什麼事
/images/emoticon/emoticon12.gif

以上就是我今天的練習啦~
/images/emoticon/emoticon08.gif

-End-


上一篇
[Day-20] 呼叫自訂函式(一)
下一篇
[Day-22] 呼叫自訂函式小練習
系列文
腦力激盪C++30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言