[Prog] C and curly braces - question of style?

Finne Boonen hennar at gmail.com
Mon Aug 23 00:55:20 EST 2004


On Sun, 22 Aug 2004 18:28:39 -0400, aec <brat at magma.ca> wrote:
> Hello,
>
> I have recently begun what is looking like a long
> and difficult journey into learning C.
>
> I am doing this from a book (Programming in C, Stephen Kochan)
> and from a tutorial I found online.
>
> At this point I am working on little examples intended
> for no other use but to teach.
>
> I am told my "style" of using curly braces {} in loops
> is not generally the best way to do it.

style of curly braces? I'm confused :)
Do you mean where you place the {} or do you mean the actual looping
construct(for, while)?

>
> Here is what I type for example inside a function:
>
>         tri_number = 0;
>         for (number = 1; number <= 15; ++number)
>         {
>                 tri_number = tri_number + number;
>                 printf("%2i     %i\n", number, tri_number);
>         }
>
> I am told however, that if you start a "for" loop, this is clearer:
>
>         tri_number = 0;
>         for (number = 1; number <= 15; ++number) {
>                         tri_number = tri_number + number;
>                         printf("%2i     %i\n", number, tri_number);
>         }
>
> To me, its not clearer, but who am I to argue at this point,
> but for now, id like to continue doing it my way and worry
> about actual syntax rather than style. Style isnt worth much
> if your programs dont work right?

why is the second example more difficult for you?
for me it's more difficult because of the way the braces are placed,
but you can just as easily put it like this:

for (number = 1; number <= 15; ++number)
{
          tri_number = tri_number + number;
          printf("%2i     %i\n", number, tri_number);
}


wich is the way I prefer it (wastes more lines, but is a lot more readable imho)

but onto the real issue, for loops are ussually prefered over while
loops because you have the increment (++number), the ending
condition(number <=15) and the initial condition(number=1) are
conveniently placed together. You have less chance of forgetting one
of them.

Finne


More information about the Programming mailing list