bug-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: pointer by reference with g++ optimisation


From: Thomas Maeder
Subject: Re: pointer by reference with g++ optimisation
Date: 17 Jul 2002 19:59:11 +0200
User-agent: Gnus/5.0808 (Gnus v5.8.8) XEmacs/21.4 (Common Lisp)

address@hidden (passing-by) writes:

> could someone explain why I am seeing different results in the code
> below depending on whether the code is compiled with optimisation or not
> (the unoptimized code produces the results i expect).

Your program has undefined behavior.


> #include <stdio.h>
> 
> void func(void){
>     printf("func");
> }
> 
> void set(void *& ptr){
>     ptr = (void*)func;
> }
> 
> int main (void) {
>     void (*fptr)(void) = 0;
>     set((void*)fptr);

There's nothing in the language definitions that allows a function pointer
to be converted into a void pointer. In particular, you can't expect that
the opposite conversion yields a usable function pointer.

What do you get if you try a correct program, e.g.:

#include <cstdio>

void func()
{
  std::printf("func");
}

typedef void (*fptr_type)();

void set(fptr_type &ptr)
{
  ptr = &func;
}

int main ()
{
  fptr_type fptr(0);
  set(fptr);
  fptr();

  return 0;
}

?



reply via email to

[Prev in Thread] Current Thread [Next in Thread]