簡體   English   中英

當 function 沒有顯式返回值時會發生什么? 想不通代碼的output是怎么來的

[英]what happens when function doesnt explicitly return a value? can't figure out how the output of the code is coming

我在一個測試系列中遇到了一個問題,當我根據我對 C 編程的知識手動解決時,應該給出一個 output 與給定的任何選項都不匹配。

我的 output = '++++'

問:c程序的Output是什么?

 #include <stdio.h>

 int f(int x) 
 {
     if(x==2){ return 2; } 
     else{ printf("+"); f(x-1); }
 }
 int main() 
 {
     int n = f(6); 
     printf("%d",n); 
     return 0; 
 }

選項:

  1. '++++2'(正確選項acc to answer key)
  2. '+++++2'
  3. '+++++'
  4. '2'

我的邏輯:因為最后 f(6) 沒有顯式返回任何內容[只有 f(2) 將值 2 返回到 f(3)],output 應該只包含 4 次“+”,因為每次調用 f (6)、f(5)、f(4) 和 f(3)。

以下是我在在線 c 編譯器 - 'codechef' 和 'onlinegdb' 上嘗試過的一些測試代碼及其輸出屏幕截圖 - 但我也無法理解它們的輸出。 請幫忙!

編解碼器

編解碼器

在線gdb 1

在線gdb 1

在線gdb 2

在線gdb 2

如果 function 被定義為返回一個值而它沒有,那么嘗試使用返回的值會導致未定義的行為

這記錄在C 標准的第 6.9.1p12 節中:

如果到達終止 function 的} ,並且調用者使用了 function 調用的值,則行為未定義。

這基本上意味着結果是不可預測的和/或一致的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM