switch { } - case for range

S

Simon Biber

CBFalconer said:
I disagree. The grammar needed to parse such constructs is a
horror, and the result is all sorts of silly errors. SPL (Algol
based HP System Programming Language for the HP3000) had that
construct, and it created nothing but trouble.

It could be done with a preprocessor for C. This needs a lot more work
before use in production code.

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

int main(void)
{
char *p, *q;
int pe, qe;
char line[1024];

while(fgets(line, sizeof line, stdin))
{
p = strstr(line, "<");
if(p)
{
q = strstr(p+1, "<");
if(q)
{
*p = 0;
*q = 0;
if(p[1] == '=') { pe = '='; p++; } else pe = ' ';
if(q[1] == '=') { qe = '='; q++; } else qe = ' ';
printf("%s<%c%s && %s<%c%s", line, pe, p+1, p+1, qe, q+1);
}
else
{
printf("%s", line);
}
}
else
{
printf("%s", line);
}
}
return 0;
}

Caveats: Only works once per line. Knows nothing of C syntax. Does not
detect comments or string literals.

Example:

C:\docs\prog\c>type test.c
#include <stdio.h>

void test(int a, int b, int c)
{
printf("%d lt %d lt %d = %d\n", a, b, c, a < b < c);
printf("%d lt %d le %d = %d\n", a, b, c, a < b <= c);
printf("%d le %d lt %d = %d\n", a, b, c, a <= b < c);
printf("%d le %d le %d = %d\n", a, b, c, a <= b <= c);
printf("\n");
}

int main(void)
{
test(1,2,2);

return 0;
}

C:\docs\prog\c>gcc -ansi -pedantic -Wall -W -O2 rangepp.c -o rangepp

C:\docs\prog\c>rangepp < test.c > test2.c && gcc test2.c && a
1 lt 2 lt 2 = 0
1 lt 2 le 2 = 1
1 le 2 lt 2 = 0
1 le 2 le 2 = 1
 
C

Chris Dollin

CBFalconer said:
I disagree. The grammar needed to parse such constructs is a
horror,

Not true. Why do you think this?

(The BCPL parser has something in the nature of a hack, but not
a nasty hack - the nasty bit was the code generation, which,
at least in the compiler I tinkered with, re-evaluated middle
expressions, so if they had side-effects URGH.

I've also implemented long relational expressions myself. The
grammar is peanuts. The tricky bit is just arranging to not
re-evaluate the middle expressions, and that's one of those
jobs where, once you know you have to do it, you just do it.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top