如何在while中给一个void函数赋值
时间: 2024-04-14 08:27:34 浏览: 10
在 C/C++ 中,`void` 函数不返回任何值,因此无法直接将其赋值给变量。`void` 函数通常用于执行操作而不返回结果。
如果您要在 `while` 循环中调用 `void` 函数,并且希望使用函数的执行结果进行赋值,您可以考虑使用全局变量或者传递指针作为参数来实现。
以下是两种可能的方法:
1. 使用全局变量:
- 定义一个全局变量,用于存储函数的执行结果。
- 在 `void` 函数中修改全局变量的值。
- 在 `while` 循环中使用该全局变量的值。
例如:
```cpp
// 全局变量
int result = 0;
// void 函数修改全局变量的值
void myVoidFunction()
{
result = 42;
}
int main()
{
while (true)
{
// 调用 void 函数
myVoidFunction();
// 使用全局变量的值
int value = result;
// 进一步处理...
}
return 0;
}
```
2. 传递指针作为参数:
- 将需要赋值的变量的地址作为参数传递给 `void` 函数。
- 在 `void` 函数中通过指针修改变量的值。
- 在 `while` 循环中使用已经被修改的变量。
例如:
```cpp
// void 函数通过指针修改参数的值
void myVoidFunction(int* ptr)
{
*ptr = 42;
}
int main()
{
int value = 0;
while (true)
{
// 调用 void 函数,并传递变量的地址
myVoidFunction(&value);
// 使用已经被修改的变量
int modifiedValue = value;
// 进一步处理...
}
return 0;
}
```
请根据您的具体需求选择适合的方法。如果您需要在 `void` 函数中返回值,考虑将函数的返回类型改为需要的类型,并使用 `return` 语句返回结果。