Path: utzoo!attcan!uunet!wuarchive!husc6!ngo From: ngo@tammy.harvard.edu (Tom Ngo) Newsgroups: comp.lang.c++ Subject: [SUMMARY] Three ways to declare a function "const" in C++ 2.0 Message-ID: Date: 16 Oct 90 14:26:25 GMT Sender: news@husc6.harvard.edu Distribution: comp Organization: Harvard Chemistry Department Lines: 62 Thanks to all those who replied to my (badly worded) query, posted in comp.lang.c++: ngo> In g++, you can declare a function "const", e.g. ngo> const double sin( double x ) ngo> if the function examines nothing but its arguments and has no ngo> side-effects. (Such a function can be subject to common ngo> subexpression elimination.) Is this a part of C++ 2.0? If not, ngo> why not? I say my query was badly worded because most of the replies (understandably) described "const member functions", i.e. member functions which (unless const is casted away) do not modify *this. The syntax for defining such a function would go: double sin( double x ) const { /* ... */ } My question really referred to the syntax in my original posting, i.e. const double sin( double x ) { /* ... */ } AT&T and GNU C++ treat this syntax in different ways: [AT&T] The "const" modifies the type "double", so the function returns a "const double", i.e. a double which cannot be modified. In this particular context, the "const" is meaningless--the value returned by a function to its caller can't be modified anyway. [GNU] The "const" syntax is co-opted to mean something else. It now declares something about the function itself: that if the function is called twice, and the arguments are not altered between calls, the second call to the function can be eliminated without changing the meaning of the program. This kind of const is used to eliminate redundant calculations in a sequence like double x, y, z; x = M_PI * 0.25; y = sin(x); z = sin(x); The compiler can replace this with double x, y, z; x = M_PI * 0.25; y = sin(x); z = y; My opinion, for what it's worth, is that the G++ meaning is much more useful. Tony Hansen remarked: It's a relatively new extension of g++. I'm sure that it will be considered by the ANSI committee. I'm also sure that Bjarne Stroustrup has looked at the extensions that g++ provides, but I don't think any of them have made it back into C++ in the same fashion that g++ implemented them. -- Tom Ngo ngo@harvard.harvard.edu 617/495-1768 lab number, leave message