"Herbert Rosenau" <os****@pc-rosenau.dewrites:
On Wed, 9 Aug 2006 13:28:17 UTC, Frederick Gotham <fg*******@SPAM.com>
wrote:
>bw*****@yahoo.com posted:
I am starting this thread after having run into two separate programming
problems, where the compiler offered no help. The compiler did not even
warn. The programs compiled fine. And the programs even appeared to
work.
Computers are our slaves. Your code told the computer what to do, so it did
it.
The first case was passing directly a variable of type char **.
Here's an example:
prototype: void func(char **);
WRONG
char **var;
func(var);
I presume you would like a warning such as:
usage of uninitialised variable
Become more familiar with pointer variables and you won't be making such
mistakes.
The second problem I ran into was typecasting an integer to a pointer.
For example:
int var;
foo((void *)var);
The above causes a problem since a pointer and an integer are two
really different types of variables.
So why perform the cast?
The problem is that function required a pointer to be passed, but I
needed to work with an integer in the function I was calling.
What, something like this:
void Func(void *p)
{
int i = (int)p;
enters UB. a pinter is not an int. So casing it to int will produce
something but seldom what you thinks it should produce.
Casting a pointer to int does not *necessarily* invoke undefined
behavior. C99 6.3.2.3p6:
Any pointer type may be converted to an integer type. Except as
previously specified, the result is implementation-defined. If the
result cannot be represented in the integer type, the behavior is
undefined. The result need not be in the range of values of any
integer type.
(The phrase "Except as previously specified" refers to null pointer
constants.) If your implementation provides intprt_t and/or
uintptr_t, you can convert a void* to either of those types without
risk of undefined behavior.
That's not to say that converting pointers to integers is a good idea.
If you're writing low-level code *and* you know exactly what you're
doing, it can be useful. If not, you should avoid it. Pointers are
pointers, and integers are integers.
> DoSomething(i);
}
int main()
{
int i = 5;
Func( (void*)i );
}
That's a horrid design (and isn't guaranteed to work).
It is goiaranteed NOT to work.
No, it's not guaranteed not to work. If the implementation allows int
and void* to be converted back and forth, it could do exactly what you
want it to do. But yes, it's most likely a horrid design, unless
there's some really good reason to do it that way.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.