TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: William McBrine
from: Roy J. Tellason
date: 2003-08-28 04:06:28
subject: QWK problem(s)

William McBrine wrote in a message to Roy J. Tellason:

-=> Roy J. Tellason wrote to William McBrine <=-

 WM> unsigned getshort(const unsigned char *x)
 WM>  ...

 RJT> What's the effect of that "const" in there?

 WM> It indicates to the compiler that the value pointed to by x will
 WM> not be modified by getshort(). So this function can take both const
 WM> and non-const parameters. Without it, one might get a warning when
 WM> calling it with a const parameter.

 RJT> So you'd use one when the function is called, to make it match.

 WM> NO. What did I just say? "[It] can take both const and non-const
 WM> parameters." NOT having to cast the parameters on calling is the
 WM> whole point.

 WM> There are some commonplace functions that don't modify the values
 WM> they're passed, but which are traditionally declared with non-const
 WM> parameters: 

 WM>     void somefunc(char *x)
 WM>     {
 WM>       ...
 WM>     }

 WM> So when you attempt to pass a const char * to one of these 
 WM> functions, you have to explicitly cast it, or you'll get a compiler
 WM> warning: 

 WM>     const char *y = "whatever";
 WM>     ...
 WM>     somefunc((char *) y);

 WM> Very annoying.

I can see where it would be.  And I didn't know about that...

 WM> But if the function were declared with a const parameter, there'd 
 WM> be no need to cast when calling it (neither for a const nor 
 WM> non-const parameter):

 WM>     void someotherfunc(const char *x)
 WM>     {
 WM>       ...
 WM>     }

 WM>     const char *y = "whatever";
 WM>     char z[] = "foo";
 WM>     ...
 WM>     someotherfunc(y);
 WM>     someotherfunc(z);

Ok,  that's clear to me now.

 WM> Of course, the alternative (bad) solution would be to just declare
 WM> y as a char * in the first place, even though you never intended to
 WM> modify it.   That way, if you accidentally did attempt to modify *y
 WM> later (think of the difference between "=" and
"=="), the compiler
 WM> wouldn't know to warn you about it; nor would it be able to perform
 WM> any potential optimizations for read-only variables if it didn't
 WM> know they were supposed to be read-only. 

Good points,  there.

--- 
* Origin: TANSTAAFL BBS 717-838-8539 (1:270/615)
SEEN-BY: 633/267 270
@PATH: 270/615 150/220 379/1 106/1 2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.