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

时间:2017-06-03 18:49:00

标签: c if-statement

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

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

1 个答案:

答案 0 :(得分:5)

你可以:

  • 将每个if(conditition) { instructions }放入一个函数中,以便每个函数具有相同的签名
  • 创建函数指针数组
  • 洗牌阵列
  • 浏览数组并调用每个成员

(或者,如果您关注fn-call开销而不是标准合规性,则可以用GNU computed gotos替换函数指针)。

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

#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);
}