Liste des Groupes | Revenir à cl c |
Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:On 01.12.2024 13:41, Waldek Hebisch wrote:Stefan Ram <ram@zedat.fu-berlin.de> wrote:>>>
My bad if the following instruction structure's already been hashed
out in this thread, but I haven't been following the whole convo!
>
In my C 101 classes, after we've covered "if" and "else",
I always throw this program up on the screen and hit the newbies
with this curveball: "What's this bad boy going to spit out?".
>
Well, it's a blue moon when someone nails it. Most of them fall
for my little gotcha hook, line, and sinker.
>
#include <stdio.h>
>
const char * english( int const n )
{ const char * result;
if( n == 0 )result = "zero";
if( n == 1 )result = "one";
if( n == 2 )result = "two";
if( n == 3 )result = "three";
else result = "four";
return result; }
>
void print_english( int const n )
{ printf( "%s\n", english( n )); }
>
int main( void )
{ print_english( 0 );
print_english( 1 );
print_english( 2 );
print_english( 3 );
print_english( 4 ); }
>
That breaks two rules:
- instructions conditioned by 'if' should have braces,
I suppose you don't mean
>
if (n == value) { result = string; }
else { result = other; }
>
which I'd think doesn't change anything. - So what is it?
>
Actually, you should just add explicit 'else' to fix the problem.
(Here there's no need to fiddle with spurious braces, I'd say.)
Lack of braces is a smokescreen hiding the second problem.
Or to put if differently, due to lack of braces the code
immediately smells bad.
- when we have the result we should return it immediately.>
This would suffice to fix it, wouldn't it?
Yes (but see above).
Once those are fixed code works as expected...>
I find this answer - not wrong, but - problematic for two reasons.
There's no accepted "general rules" that could get "broken"; it's
just rules that serve in given languages and application contexts.
And they may conflict with other "rules" that have been set up to
streamline code, make it safer, or whatever.
No general rules, yes. But every sane programmer has _some_ rules.
My point was that if you adopt resonable rules, then whole classes
of potential problems go away.
Les messages affichés proviennent d'usenet.