chris@mimsy.UUCP (Chris Torek) (07/04/87)
In article <1261@apple.UUCP> mikes@apple.UUCP (Mike Shannon) writes: [Given a prototype like] >int open(const char* path, int flags, int mode=0); >if I do: >{ >char *pathname = "some.file"; >int i; > i = open(pathname, O_RDONLY) ..... >} > > is the above declaration really OK? since the first param isn't CONST? It is correct. Declaring the `path' parameter `const char *' tells the compiler that the `open' routine promises not to modify the object(s) to which `path' points. Passing a modifiable (non-const) array address is legal. On the other hand, given int mktemp(char *path); const char tfname[] = "/tmp/tfXXXXXX"; ... { mktemp(tfname); the compiler can (correctly) complain, since mktemp has been declared as potentially modifying the pointed-to characters, and these are in unmodifiable (const) storage. This means that on systems on which the compiler will indeed complain about such usages, header files must mark all those functions that do not modify objects: char *strcpy(char *dst, const char *src); int sprintf(char *buf, const char *fmt, ...); -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7690) Domain: chris@mimsy.umd.edu Path: seismo!mimsy!chris
meissner@xyzzy.UUCP (07/07/87)
In article <7316@mimsy.UUCP> chris@mimsy.UUCP (Chris Torek) writes: /* stuff about mktemp being called with a const char * might give a */ /* compiler warning deleted. */ > This means that on systems on which the compiler will indeed complain > about such usages, header files must mark all those functions that do > not modify objects: > > char *strcpy(char *dst, const char *src); > int sprintf(char *buf, const char *fmt, ...); Another reason to declare prototype parameters as const <type> * instead of <type> * is to tell smart optimizers that the item being passed will not be modified, and thus allowing the optimizer to make less pessimistic assumptions about variable lifetimes. -- Michael Meissner, Data General. Uucp: ...!mcnc!rti!xyzzy!meissner