[Courses] Chapter 4 Exercise 4-2 SPOILER

Mary linuxchix at puzzling.org
Mon Feb 18 13:53:52 EST 2002


On Sun, Feb 17, 2002 at 03:47:29PM -0500, Wendy Galovich wrote:
> #include <stdio.h>
> 
> /* Exercise 4-2: Program to print a block E using asterisks, where the E */
> /* has a height of 7 characters and a width of 5 characters.             */
> 
> char *;	/* the character '*' */
> 
> int main()
> {
>     * = '*';
> 
>     printf("\n");
>     printf("%c%c%c%c%c\n", *,*,*,*,*);
>     printf("%c\n", *);
>     printf("%c\n", *);
>     printf("%c%c%c\n", *,*,*);
>     printf("%c\n", *);
>     printf("%c\n", *);
>     printf("%c%c%c%c%c\n", *,*,*,*,*);
>     printf("\n");
>     return (0);
> }
> 
> I didn't see anything in the book - at least not in Chapter 4 - saying that * 
> couldn't be used as a character variable in that way, but obviously it can't. 
> So, my question is this: does anyone have a list of the keyboard characters 
> which are "legal" to use as char variables? Or maybe more importantly, which 
> are not? 

According to
http://www.strath.ac.uk/IT/Docs/Ccourse/subsection3_6_2.html, you must
start a variable name (ALL variable names, not just chars) with a
letter, and the name must consist of letters, numbers and underscores.

Don't use characters that are part of C syntax, certainly (*, {, },
;,...). To see this, imagine that YOU are trying to write a C compiler -
a program that understands C. If you encountered a * character, it would
be hard to tell whether it was a * meaning 'declare or dereference a
pointer' (as * means in C) or a * as part of a variable name.

With regard to the program above, by the way, try and adapt it so that
it can accept ANY two numbers (x and y, say) as input and print out an x
by y block, without recompiling. Being able to write routines that don't
need to be thrown out and rewritten when your boss/co-worker/self walks
along and says, "er, I wanted a 6 by 9 block" is one of the key ideas of
programming.

-Mary.

-- 
Mary
<mary at puzzling.org>



More information about the Courses mailing list