Sunday, December 6, 2009

. operator in enum

1)typedef enum errorType{warning, error, exception,}error;
main()
{
error g1;

g1=1;
printf("%d",g1);
}
Answer
Compiler error: Multiple declaration for error
Explanation
The name error is used in the two meanings. One means that it is a
enumerator constant with value 1. The another use is that it is a type name
(due to typedef) for enum errorType. Given a situation the compiler
cannot distinguish the meaning of error to know in what sense the error is
used:
error g1;
g1=error;
// which error it refers in each case?
When the compiler can distinguish between usages then it will not
issue error (in pure technical terms, names can only be overloaded in
different namespaces).
Note: the extra comma in the declaration,
enum errorType{warning, error, exception,}
is not an error. An extra comma is valid and is provided just for
programmer’s convenience.

2) typedef struct error{int warning, error, exception;}error;
main()
{
error g1;
g1.error =1;
printf("%d",g1.error);
}
Answer
1
Explanation
The three usages of name errors can be distinguishable by the compiler at
any instance, so valid (they are in different namespaces).
Typedef struct error{int warning, error, exception;}error;
This error can be used only by preceding the error by struct kayword as in:
struct error someError;
typedef struct error{int warning, error, exception;}error;
This can be used only after . (dot) or -> (arrow) operator preceded by the variable
name as in :
g1.error =1;
printf("%d",g1.error);
typedef struct error{int warning, error, exception;}error;
52
This can be used to define variables without using the preceding struct keyword
as in:
error g1;
Since the compiler can perfectly distinguish between these three usages, it is
perfectly legal and valid.
Note
This code is given here to just explain the concept behind. In real
programming don’t use such overloading of names. It reduces the readability of
the code. Possible doesn’t mean that we should use it!

No comments:

Post a Comment