Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sdd.hp.com!uakari.primate.wisc.edu!aplcen!haven!mimsy!chris From: chris@mimsy.umd.edu (Chris Torek) Newsgroups: comp.lang.c Subject: Re: (Ab)using pointers to const objects Message-ID: <27061@mimsy.umd.edu> Date: 18 Oct 90 23:36:33 GMT References: <1990Oct15.115003.29238@micrognosis.co.uk> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 56 In article <1990Oct15.115003.29238@micrognosis.co.uk> nreadwin@micrognosis.co.uk (Neil Readwin) writes: >I am trying to understand what I can do with pointers to const and non-const >objects. ... If you replace the word `const' with `readonly', everything will suddenly make sense. const int x = 12345; produces a read-only variable called `x' whose value is 12345. Any attempt to change x (with `x = 0;', e.g.) will give an error. An attempt to set a pointer to point to x will get an error unless the pointer itself points to readonly `int's: const int *p1; int *p2; p1 = &x; p2 = &x; The assignment `p2 = &x;' is `bad' because p2 points to changeable `int's and x, though an int, is not changeable. If you insert a cast you can `slip this by': p2 = (int *)&x; but if you assign through the resulting pointer (`*p2 = 0;'), the behaviour is undefined (meaning ANYTHING can happen, ANY time: if the computer has access to a time machine it can go back and kill your grandfather, or whatever). Most likely: a runtime error, or x changes; less likely: a compile time error; fairly unlikely: the computer explodes. In the other direction, things are better: int y; const int *p1; int *p2; p1 = &y; p2 = &y; Both assignments are legal, because in both cases `y' is an int. Although p1 points to readonly ints rather than regular ints, the only effect this has is to make attempts to change *p1 illegal. Note that *p1 can still change; it is only changes through the name `*p1' that are illegal: y = 1; printf("%d\n", *p1); /* prints 1 */ y = 2; printf("%d\n", *p1); /* prints 2 */ *p1 = 3; /* is an error */ In other words, `*p1' is NOT constant, just read-only. Every time you read it you may get a different value. (This is the sort of thing that makes alias analysis in C difficult. Not impossible, but definitely difficult. You can answer the question `does *p1 change' with `yes' or `no' in many actual programs, although there exist unsolvable cases.) -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 405 2750) Domain: chris@cs.umd.edu Path: uunet!mimsy!chris