[comp.unix.wizards] ``Constants'' in case

igb@fulcrum.bt.co.uk (Ian G Batten) (09/27/89)

Should this code fragment compile under (1) pcc (2) an ANSI compiler?

int x;

switch (x)
{
  case (int) 1:
   printf ("1\n");
   break;
  case (int) 2:
   printf ("2\n");
   break;
}

At least one compiler here rejects this, saying the case does not reduce
to a constant expression.  In fact, I suspect the general problem is
``is (int) constant a constant?''

ian

henry@utzoo.uucp (Henry Spencer) (09/30/89)

In article <62@masalla.fulcrum.bt.co.uk> igb@fulcrum.bt.co.uk (Ian G Batten) writes:
>Should this code fragment compile under (1) pcc (2) an ANSI compiler? ...
>  case (int) 1:		...
>At least one compiler here rejects this, saying the case does not reduce
>to a constant expression.  In fact, I suspect the general problem is
>``is (int) constant a constant?''

In K&R1, the list of operators allowed in constant expressions did not
include casts.  This was probably an oversight (casts were a recent addition
to the language at the time).  Casts are legal there in ANSI C.
-- 
"Where is D.D. Harriman now,   |     Henry Spencer at U of Toronto Zoology
when we really *need* him?"    | uunet!attcan!utzoo!henry henry@zoo.toronto.edu

matt@oddjob.uchicago.edu (Mens Sana in Campari Soda) (10/01/89)

igb@fulcrum.bt.co.uk (Ian G Batten) writes:
) >``is (int) constant a constant?''

henry@utzoo (Henry Spencer) writes:
) In K&R1, the list of operators allowed in constant expressions did not
) include casts.  This was probably an oversight

If you're thinking of buying any book on C, look to see how they define
"constant expression".  I looked in the local bookstore here and found a
number of titles such as "Absolutely complete ultimate C book!" which
either did not define the term at all or simply defined it as "any
expression involving only constants."   Bah!
________________________________________________________
Matt Crawford	     		matt@oddjob.uchicago.edu