"Nico Heinze" <[EMAIL PROTECTED]> wrote:
> "thos_fernando" <thos_fernando@> wrote:
> > I came across a C statement as below.
> > typedef enum {False, True}  boolean;

That is not a statement, it's a declaration.

> > I was wondering if someone could explain how this would
> > work,preferably with an example.

How did it work in the code where you saw it?

> > I know that 
> > typedef enum {False,True}; would mean that False=0 and
> > True=1.

[It would mean that even without the typedef keyword.]

> > How does the word boolean play a part ? AFAIK boolean is
> > not a C keyword. How would this be used while programming?
> 
> ... The "typedef" keyword tells the compiler that from this
> point onward (subject to scope rules, but that's a different
> matter) the term "boolean" will always mean "enum {False,
> True}". "typedef" is used to create a new name for a
> particular type.
> 
> An easy example: Usually in C you would have to write
> 
> enum {False, True} flag1;
> enum {False, True} flag2;
> enum {False, True} flag3;

Since that isn't C, I don't see why I would usually have
to write it that way! :-)

I may write it as...

  enum boolean { False, True };

  enum boolean flag1;
  enum boolean flag2;
  enum boolean flag3;

> now with this new name for the type you can simply use:
> 
> boolean flag1;
> boolean flag2;
> boolean flag3;
> 
> which makes your code easier to read (and safer against some
> typos).

Typedef is a way of saying, don't create objects, create type
names.

Consider this declaration...

  int i, *ip, (*vfi)(void);

Here we create objects with the types: int, int *, and pointer
to a function taking no parameters returning an int.

If we put typedef at the front of the declaration, we change
to the declaration to mean declare type names instead of
objects...

  typedef int i, *ip, (*vfi)(void);

We can now use the typenames to declare objects...

  i my_int;
  ip my_int_pointer;
  vfi my_pointer_to_function_returning_int;

You can't do this with every object delcaration, but it's
a good way to think of how typedef works.

As an aside, the peculiar implementation of typedef in the
grammar means that you can make some wierd, but perfectly
valid declarations...

  struct node { struct node *next; int i } typedef node_t;

-- 
Peter

Reply via email to