home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!digex.com!access.digex.com!lastort
- From: lastort@access.digex.com (Mike Lastort)
- Subject: Re: HELP with C syntax checking programm
- Message-ID: <lastort.724098713@access.digex.com>
- Keywords: c help braces { } fix syntax
- Sender: usenet@access.digex.com
- Nntp-Posting-Host: access.digex.com
- Organization: Express Access Online Communications, Greenbelt, Maryland USA
- References: <Bz3pCy.380@access.digex.com>
- Distribution: all
- Date: Fri, 11 Dec 1992 18:31:53 GMT
- Lines: 91
-
- 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 hve no problem when I do 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("brachek2.c","r");
-
- > while ((ch =getc(fptr)) !=EOF) //gets chars
- > {
- > if(ch=='{') l++;
- > if(ch=='}') r++;
- > }
- > if (l != r)
- > printf("\nBraces do not match\n");
- > else printf("\nBraces match !!!\n");
- > fclose(fptr);
- > return(0);
- >}
- >=========================== End Hack ===============================
-
- >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) //gets chars
- > {
- > switch (ch)
- > {
- > case '{': l++;
- > 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.
-
-
- Ok, the problem is that when using a switch case, you need to break out,
- or else you "fall through" to the next case. In other words, your code:
-
-
- switch (ch)
- {
- case '{': l++;
- case '}': r++;
- }
-
- will increment BOTH l and r if ch == '{', and increments r if ch == '}'.
- You should do something like:
-
-
- switch (ch)
- {
- case '{': l++; break;
- case '}': r++;
- }
-
- That way, if ch == '{', l gets incremented, then the next character is
- examined.
-
- Mike
-
-