1.When you declare something with #define then you are asking the preprocessor for just the symbol substitution. So #define is global in scope, even if u give a #define statement inside a namespace or class it will still have global effect. 2. Eventhough constant also declares a constant as done by #define, here type checking will be performed. Another thing is that you cannot have constants inside a class.(even if u declare one it will be treated as static by the compiler). And its scope is limited by the block in which it is declared. 3. If u want a constant inside a class then u should use enum. Enum’s scope is also limited to the block in which you declared it.
for ex: namespace MyNamespace { #define ONE 10
enum { TWO = 20};
int const three = 3; }
class test{ #define ONE 1 enum{ TWO=2}; int const three; }; int main() { test t; // will flag a error here with “structure `t’ with uninitialized const members” ONE; /* No problem */ TWO; /* Can’t find it */ three; /* Can’t find it */
test::ONE; /*syntax error before `1′ */ MyNamespace::TWO; /* No probtem */ MyNamespace::three; /* No problem */ }
kiran kumar katreddi said
1.When you declare something with #define then you are asking the preprocessor for just the symbol substitution. So #define is global in scope, even if u give a #define statement inside a namespace or class it will still have global effect.
2. Eventhough constant also declares a constant as done by #define, here type checking will be performed. Another thing is that you cannot have constants inside a class.(even if u declare one it will be treated as static by the compiler). And its scope is limited by the block in which it is declared.
3. If u want a constant inside a class then u should use enum. Enum’s scope is also limited to the block in which you declared it.
for ex:
namespace MyNamespace {
#define ONE 10
enum { TWO = 20};
int const three = 3;
}
class test{
#define ONE 1
enum{ TWO=2};
int const three;
};
int main()
{
test t; // will flag a error here with “structure `t’ with uninitialized const members”
ONE; /* No problem */
TWO; /* Can’t find it */
three; /* Can’t find it */
test::ONE; /*syntax error before `1′ */
MyNamespace::TWO; /* No probtem */
MyNamespace::three; /* No problem */
}
surya kiran said
What ares the differences between
a) enum
b) const
c) # defines. Compare the three ? Explain with an example ?