-
Swich/Case Question
Is there any way to make a switch/case statement work for values that aren't known at runtime. I don't see why it couldn't work with variables, but my complier only seems to allow constants. I'm not picky about the method that's used but I'd perfer it would be something a little more efficient than and endless bunch of if/elses, which is the only thing I could come up with as an alternative.
-
Xzyx987X,
Is this what you mean?
Code:
#include <stdio.h>
int main(void)
{
/* use a character as the switch variable */
char c = '1';
unsigned int done = 0;
while (!done)
{
switch (c)
{
case '1':
printf("case 1\n");
c = '2';
break;
case '2':
printf("case 2\n");
c = '4';
break;
case '3':
printf("case 3 (doesn't print)\n");
c = '4';
break;
case '4':
printf("case 4\n");
c = '5';
break;
default:
done = 1;
break;
}
}
}
/* similar to above except the switch variable is an integer
int main(void)
{
unsigned int x = 1;
unsigned int done = 0;
while (!done)
{
switch (x)
{
case 1:
printf("case 1\n");
x++;
break;
case 2:
printf("case 2\n");
x = 4;
break;
case 3:
printf("case 3 (doesn't print)\n");
x++;
break;
case 4:
printf("case 4\n");
x++;
break;
default:
done = 1;
break;
}
}
}
*/
-
No, not really. What I meant was something like this, only that worked:
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n = rand() % 10;
int i;
int numArray[4];
for(i = 0; i < 4; i++)
numArray[i] = rand() % 10;
switch (n)
{
case numArray[0]:
printf("case 1\n");
break;
case numArray[1]:
printf("case 2\n");
break;
case numArray[2]:
printf("case 3\n");
break;
case numArray[3]:
printf("case 4\n");
break;
}
return 0;
}
Edit: One thing I'm definately aware of is that this would problbly take some dynamically generated ASM code to do, so don't tell me this is impossible just because it can't be done in pure C :P.
-
You would need to use if/else type logic for this
-
An alternative approach
Code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int main(void)
{
int n;
int i;
int numArray[SIZE];
srand(time(NULL));
n = rand() % 10;
for (i = 0; i < SIZE; i++)
{
numArray[i] = rand() % 10;
}
printf("Looking for %d\n", n);
for (i = 0; i < SIZE; i++)
{
printf("Checking element %d (value:%d)\n", i, numArray[i]);
if (numArray[i] == n)
{
break;
}
}
if (i < SIZE)
{
printf("Found %d in element number %d\n", n, i);
}
else
{
printf("Failed to find it!\n");
}
return(0);
}
/* Sample Output:
Looking for 1
Checking element 0 (value:9)
Checking element 1 (value:8)
Checking element 2 (value:0)
Checking element 3 (value:1)
Found 1 in element number 3
*/