我試圖在不使用全域變數的情況下從另一個函式列印 main 內部的區域變數的值。最好的方法是什么?
#include <stdio.h>
int function1();
int main(void) {
int hello=10;
printf(function1());
}
int function1(int ip){
printf("hello%d",ip);
}
我希望10將 列印在旁邊,"hello"但得到一個 0。
uj5u.com熱心網友回復:
您需要呼叫傳遞所需值(或變數)的函式。
int function1(int);
int main(void)
{
int hello=10;
function1(hello);
function1(130);
}
int function1(int ip)
{
return printf("hello - %d\n",ip);
}

構建警告:
最后,運行時錯誤:


從這些您可以開始得出以下一些觀察結果(列出的其他觀察結果是我自己的。)
- 函式原型的簽名必須與其實作相匹配。(對于function1,他們沒有)
- 如果函式的原型是非空的,那么它應該回傳一個值。
- 如果函式回傳一個值,則不應忽略其回傳值。
- 未使用變數的警告指出您可能打算在此處將其用作引數:
function1()
有關其他說明,請參閱下面的評論:
int function1();//this prototype is incomplete, and is inconsistent
//with the signature of its implementation
int main(void) {
int hello=10;
printf(function1());//because function1 does not return a value, your code outputs a 0
// non-void function should return a value here
}
int function1(int ip){//signature of this implementation disagrees with its prototype
//because there is no value passed, ip can be any value
printf("hello%d",ip);
// non-void function should return a value here
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/530472.html
標籤:C
下一篇:列印除數之和最高的數字
