problem with const in structure
Daniel Schüle" <[email protected]>
Quoted 19 lines
#include <
stdio.h>struct node {
const int x;
char name[20];
struct node *next;
};int
main()
{
struct node newnode;newnode.x = 10;
newnode.x = 12;
printf ("x = %d\n", newnode.x);
return 0;
}
####
Quoted 5 lines
Now, you can see that even though I have defined x to be const int, I can assign it values. When I compiled the program, it gives the warning that assignment of read-only member x but when I ran the program, it worked fine. Where is the catch. How do I define a structure variable to be const?
Welcome in C World (which is mainly non const :))
In C++ it's easy to fix
struct node
{
node(int x_, node * left_=0, node * right_=0) : x(x_), left(left_),
right(right_)
{
x = x_; // is *always* compile time error (in C++), because
// you are altering const variable
// in C++ you have to be aware that assignment and initialization
are *not* the same thing
// they might seem for some to act similar and in some contexts
they do
}
// const node * root;
const int x;
node * left, * right;
};int i = 0; // is initialisation of non const varibale
i = 0; // assignment
const int null; // error, const must be initialized
null = 0; // error
const int null = 0; // ok, in this way or
const int null(0); // or
const int null = int(0);
Daniel.
--
$>fortune
the generation of random numbers is too important
to be left to chance.