gpt4 book ai didi

c - 如何删除多余的循环?

转载 作者:太空宇宙 更新时间:2023-11-04 01:16:25 24 4
gpt4 key购买 nike

我需要使代码更具可读性,但它有很多循环,我能以某种方式解决这个问题吗?

变量i不停地跳来跳去,调试时很不方便看。

for(;;)
{
//
// For connection orientated protocols, we will handle the
// packets received from a connection collectively. For datagram
// protocols, we have to handle each datagram individually.
//

//
// Check to see if we have any sockets remaining to be served
// from previous time through this loop. If not, call select()
// to wait for a connection request or a datagram to arrive.
//

for (i = 0; i < numSocket; i++)
{
if (FD_ISSET(servSock[i], &SockSet))
break;
}

if (i == numSocket)
{
for (i = 0; i < numSocket; i++)
{
FD_SET(servSock[i], &SockSet);
}

if (select(numSocket, &SockSet, 0, 0, 0) == SOCKET_ERROR)
continue;
}

for (i = 0; i < numSocket; i++)
{
if (FD_ISSET(servSock[i], &SockSet))
{
FD_CLR(servSock[i], &SockSet);
break;
}
}

...

}

最佳答案

为了使代码更具可读性(以及可测试性和可维护性),您可以将一些逻辑封装到具有有意义名称的单独函数中。考虑这个版本的循环

for(;;)
{
int i = find_socket_to_be_served(numSocket, servSock, &SockSet);

if (i == numSocket)
{
set_all_sockets(numSocket, servSock, &SockSet);

if (select(numSocket, &SockSet, 0, 0, 0) == SOCKET_ERROR)
continue;
}
// ...
}

其中使用的两个函数定义为

int find_socket_to_be_served(int n_sockets, int *fds, fd_set *fdset)
{
int i = 0;
for (; i < n_sockets; i++)
{
if (FD_ISSET(fds[i], fdset))
{
FD_CLR(fds[i], fdset);
break;
}
}
return i;
}

void set_all_sockets(int n_sockets, int *fds, fd_set *fdset)
{
for (int i = 0; i < n_sockets; i++)
{
FD_SET(fds[i], fdset);
}
}

关于c - 如何删除多余的循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57883585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com