I want a new C construct
I find myself missing a flow of control construct in C. Let’s say I want to locate a value which might come from a number of sources then do something with it.
if ( code == 36) value = 99; else { // a bunch of code to see if it is
in the cache if ( code_in_cache(code)) value =
code_from_cache(code); else { // notice how each place I have to look
is //accumulating nesting?
… }
}
If I were willing to split the code into a separate function I could
just use return
e.g.
int gratuitous_function( int code) { if ( code == 36) return 99;
// a bunch of code to see if it is the cache
if ( code_in_cache(code)) return code_from_cache(code);
// notice how I am not accumulating nesting?
…
}
That is better, but I don’t like breaking the linear flow of the program and it is likely that the function will require access to many of my local variables making a complicated interface. Worse, I may be setting several values and that gets ugly.
I generally try to cope like this…
do {
if ( code == 36) { value = 99; break; }
// a bunch of code to see if it is in the cache
if ( code_in_cache(code)) { value = code_from_cache(code);
break; } // notice how I am not accumulating nesting? … } while(0);
That works fine until I locate the value inside a for loop, then the
break
will take it out of the for loop.
I think what I really want is a named block…
block foo {
if ( code == 36) { value = 99; break foo; }
// a bunch of code to see if it is in the cache
if ( code_in_cache(code)) { value = code_from_cache(code); break
foo; } // notice how I am not accumulating nesting? … }
I guess I could always be a barbarian just use a goto
and a label.
if (code == 36) {
value = 99;
} else if (code_in_cache(code)) {
value = code_from_cache(code);
} else if (...) {
// Notice how there is no nesting?
}