From: jens on
Hi Everybody

I have question regarding switch statements.

Is there a limit how many cases a switch statement can contain?Now I have a switch statement with about 100 cases.

Best Regards

Jens
From: Ashish Uthama on
On Fri, 09 Apr 2010 15:37:04 -0300, jens <storebonghoved(a)hotmail.com>
wrote:

> Hi Everybody
>
> I have question regarding switch statements.
>
> Is there a limit how many cases a switch statement can contain?Now I
> have a switch statement with about 100 cases.
>
> Best Regards
>
> Jens

I am curious to know why one would have to test these limits. Maybe you
can say more about your use and someone here might suggest an alternate
solution (better than having 100+ cases).

If you _have_ to, heres a toy:



clear all;
N=2000;

%Auto generate code like this
%
% for sindx=1:N
% switch(sindx)
% case 1
% disp(1);
% case 2
% disp(2);
% %.till N
% end
% end

f=fopen('tswitch.m','wb');
fprintf(f,'for sindx = 1:N\n');
fprintf(f,' switch(sindx)\n');

for lindx=1:N
fprintf(f,' case %d\n',lindx);
fprintf(f,' disp(%d)\n',lindx);
end

fprintf(f,'end\nend\n');
fclose(f);

%Run the test we just created
tswitch
From: Jan Simon on
Dear Jens!

> Is there a limit how many cases a switch statement can contain?Now I have a switch statement with about 100 cases.

I have not seen the underlying assembler code, so it is possible that the number of cases is limited to 2^16 or 2^32.

Such a large SWITCH is rather inefficient, because in average the number of comparisons is the half of the case statements.

Jan
From: Matt Fig on
What on Earth could you need so many cases for?
From: Jan Simon on
Dear Matt!

> What on Earth could you need so many cases for?

E.g. pseudo hardware random number generator. You gauge it with a real fair unbiased dice. Then:

function X = RND
persistent n
if isempty(n)
n = uint32(1);
else
n = n + 1;
end
switch n
case 1, X = 4;
case 2, X = 2;
case 3, X = 6;
case 4, X = 3;
etc... % I think you got it now
otherwise
X = 1;
n = 0;
end
return;

Much better than the old-fashioned modulo and bitshift stuff. I admit, it took a while until 2^32-1 cases have been programmed. The program would run faster, if we had the "n++" operator in Matlab.

Jan