gpt4 book ai didi

随机检查C中的几个If条件

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

我有一个 C 语言程序,其中有几个 if 条件,如下所示:
if(condition 1) {instructions}<br/>
if(condition 2) {instructions}<br/>
if(condition 3) {instructions}<br/>
// and some other conditions

无论如何,当我每次运行程序时,Ifs 的检查顺序随机重新排列,例如如下所示:
if(condition 3) {instructions}<br/>
if(condition 1) {instructions}<br/>
if(condition 2) {instructions}<br/>
// and some other conditions

最佳答案

你可以:

  • 将每个if(conditition) {指令}放在一个函数中,使每个函数具有相同的签名
  • 创建指向函数的函数指针数组
  • 打乱数组
  • 遍历数组并调用每个成员

(或者,如果您担心 fn 调用开销而不是标准合规性,您可以将函数指针替换为 GNU 计算的 goto)。


下面是一个基于计算的 goto 的例子,它在这里用作更便宜的、可寻址的函数:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void shuffle(void *obj, size_t nmemb, size_t size);

#define ARRAY_SIZE(A) (sizeof(A)/sizeof(A[0]))

int main(int c, char **v)
{
int n = c>1 ? atoi(v[1]) : 0;
void *ret=&&ret_lbl;
int i;
srand(time(0));

void *checks[] = { &&lt_10, &&lt_100, &&lt_1000, &&lt_10000 };
shuffle(checks, ARRAY_SIZE(checks), sizeof checks[0]);

for(i=0; i<ARRAY_SIZE(checks); i++){
goto *checks[i];
ret_lbl:;
}

return 0;

/*the if checks*/

lt_10: if (n < 10) puts("lt_10");
goto *ret;
lt_100: if (n < 100) puts("lt_100");
goto *ret;
lt_1000: if (n < 1000) puts("lt_1000");
goto *ret;
lt_10000: if (n < 10000) puts("lt_10000");
goto *ret;

}


/* From
http://rosettacode.org/wiki/Knuth_shuffle#C
*/
int rrand(int m)
{
return (int)((double)m * ( rand() / (RAND_MAX+1.0) ));
}

#define BYTE(X) ((unsigned char *)(X))
void shuffle(void *obj, size_t nmemb, size_t size)
{
void *temp = malloc(size);
size_t n = nmemb;
while ( n > 1 ) {
size_t k = rrand(n--);
memcpy(temp, BYTE(obj) + n*size, size);
memcpy(BYTE(obj) + n*size, BYTE(obj) + k*size, size);
memcpy(BYTE(obj) + k*size, temp, size);
}
free(temp);
}

关于随机检查C中的几个If条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44347441/

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