home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!usc!cs.utexas.edu!csc.ti.com!tilde.csc.ti.com!mksol!mccall
- From: mccall@mksol.dseg.ti.com (fred j mccall 575-3539)
- Subject: Re: Problems with Case statements HELP!
- Message-ID: <1992Dec15.172351.21579@mksol.dseg.ti.com>
- Keywords: case help lost c not
- Organization: Texas Instruments Inc
- References: <Bz18KA.MCv@access.digex.com>
- Distribution: usa
- Date: Tue, 15 Dec 1992 17:23:51 GMT
- Lines: 73
-
- In <Bz18KA.MCv@access.digex.com> jhurwitz@access.digex.com (j. hurwitz) writes:
-
-
- >Okay, I'm new to C so you'll have to forgive my lame question. Anyhoot,
- >I'm trying to write a program that will check for balanced braces in my
- >C source code. I have no problem when I do this:
-
- >=========================== Begin Hack =============================
- >//programm to read a C source file and verify # of left to right braces
-
- >But, when I try this:
-
- >============================== Begin Hack =========================
- >//programm to read a C source file and verify # of left to right braces
-
- >#include <stdio.h>
- >int main(int argc, char *argv[])
- >{
- > FILE *fptr;
- > int l=0, r=0;
- > char ch;
-
- > fptr = fopen("brachek3.c","r");
- > while ((ch =getc(fptr)) !=EOF)
- > {
- > switch (ch)
- > {
- > case '{': l++;
- <<---- fall through case.
- > case '}': r++;
- > }
- > }
- > printf("\nl= %d r= %d", l, r);
- > if (l != r)
- > printf("\nBraces do not match\n");
- > else printf("\nBrace match !!!\n");
- > fclose(fptr);
- >}
- >================================ End Hack ========================
- >I get an uneven number of braces at the end. I can't figure out what
- >I am doing wrong. I'm sure it is a minor oversight on my part. Any help
- >would be greatly appreciated
-
- In C, each case is simply a label and will fall through to the end of
- the switch unless it encounters a 'break' statement to end it. Each
- time you find a '{' you are incrementing both r and l. Each time you
- find a '}' you are incrementing only r. Given the code, r will exceed
- l by the number of '}' characters you find. If things are balanced,
- it will be twice l.
-
- Your switch should read:
-
- switch (ch) {
- case '{':
- l++;
- break;
- case '}':
- l++;
- break;
- default:
- /* Do nothing */
- break;
- }
-
- A lot of people think that including the empty default (or putting a
- break on the default case, period) is a bit anal retentive, so handle
- it however you are comfortable.
-
- --
- "Insisting on perfect safety is for people who don't have the balls to live
- in the real world." -- Mary Shafer, NASA Ames Dryden
- ------------------------------------------------------------------------------
- Fred.McCall@dseg.ti.com - I don't speak for others and they don't speak for me.
-