【发布时间】:2018-02-11 10:52:45
【问题描述】:
我来自一门主要面向对象的编程语言,并试图更多地理解 C 的功能,因此决定编写一个小程序来完成这项工作。
我遇到的问题是通常使用 DI 解决的问题,如何将值的引用传递给另一个函数,以便它可以在不使用全局变量的情况下对其执行算术运算?
考虑以下程序:
#include <stdio.h>
#include <stdlib.h>
int doStuff(int v)
{
v = v + 10; // main->value = 10
}
int otherStuff(int v)
{
v = v - 10; // main->value = 0
}
int main()
{
int value = 0;
int stop = 0;
do
{
printf(" %i should be 0 \n", value);
doStuff(value); // "value" = 10
printf(" %i should be 10 \n", value);
otherStuff(value); // "value" = 0
printf(" %i should be 0 \n", value);
exit(0);
if(value >= 10)
{
stop = 1;
}
} while(!stop);
}
输出:
0 should be 0
0 should be 10
0 should be 0
【问题讨论】: