home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!zaphod.mps.ohio-state.edu!pacific.mps.ohio-state.edu!linac!att!bu.edu!news.tufts.edu!news.tufts.edu!gowen
- From: gowen@jade.tufts.edu (G. Lee Owen)
- Newsgroups: comp.lang.c
- Subject: Re: If statement question
- Message-ID: <GOWEN.92Nov22235007@jade.tufts.edu>
- Date: 23 Nov 92 04:50:38 GMT
- Sender: news@news.tufts.edu (USENET News System)
- Distribution: na
- Organization: Tufts University - Medford, MA
- Lines: 65
-
-
-
- Sorry, took me a day extra to get this out, but here we go...
-
- From ckkoo@magnus.acs.ohio-state.edu (Chee K Koo) on 20 Nov 92:
- CKK> I am new to C programming, while i was doing a numerical analysis
- CKK> program which uses many for loop
- CKK> here is the loop looks like
- CKK> for(i=1;i<=n;i++);
- CKK> {
- CKK> }
- CKK> i put the ";" after the loop header, when the program is excuted, the
- CKK> loop is skipped, however, it works fine when the ";" is removed.
-
- When you say 'for(i=1;i<=n;i++);' you are really telling the
- compiler 'for(i=1;i<=n;i++) /* DO NOTHING */;'. The for loop will
- work on the (single) statement following it OR on the block following
- it, where { and } mark off the block.
- If you were writing a loop that would execute one statement, it
- would be like this, right?
- for(i=1;i<=n;i++) printf("Hi #%d\n", i);
- Notice how there is no ; between the end of the loop parens and the
- printf statement. Well, the same thing goes for a for loop with a
- block following it. Say you had to execute two statements, you would
- put them in a block:
- for(i=1;i<=n;i++)
- {
- printf("Hi ");
- printf("#%d\n", i);
- }
- like such. The output of this would be (n == 5 here)
- Hi 1
- Hi 2
- Hi 3
- Hi 4
- Hi 5
- Notice that, without the blocks, like this:
- for(i=1;i<=n;i++)
- printf("Hi ");
- printf("#%d\n", i);
- it will print "Hi " n times and then print "#i" where i has the same
- value as n. If n equalled 5 you would get "Hi Hi Hi Hi Hi 5".
-
- I'm afraid I find this difficult to explain succinctly; I hope
- these examples illustrate what you are seeing. Perhaps you should dig
- in your textbook a bit more...
-
- CKK> I just want to find out why the compiler does not catch it during
- CKK> compilation. It is compiled with UNIX gcc.
- Well, frankly, it's not the compiler's job. More importantly,
- neither would it always be correct to flag that. Consider this:
- for (i=0; ((i<ARRAY_MAX)&&(array[i]!=42)); i++) /* DO NOTHING */ ;
- printf("The Answer to Life is at array position %d\n", i);
- This fragment uses the loop to find the position in the array which
- holds the value 42; the loop need not execute a statement, and the
- side effect is that when the loop terminates, i has the value we are
- interested in.
-
- Hope this helps explain...
-
-
- --
- --Greg Owen
- gowen@forte.cs.tufts.edu, gowen@jade.tufts.edu
- "C Spot. C Spot run. C Spot run without a core dump! Run, Spot, Run!"
-