un-expected side-effect of function call

Mathieu Lacage mathieu.lacage@gmail.com
Wed Sep 30 07:31:00 GMT 2009


hi,

While debugging a piece of code which was not setting a boolean
correctly to true, I stumbled upon this (reduced) testcase:

#include <iostream>

static bool g_error = false;

bool foo (void)
{
  g_error |= true;
  return false;
}

int main (int argc, char *argv[])
{
  std::cout << g_error << std::endl;
  g_error |= foo ();
  std::cout << g_error << std::endl;

  return 0;
}

This code prints: 0 + 0 but the following C program:

#include <stdio.h>

static int g_error = 0;

int foo (void)
{
  g_error |= 1;
  return 0;
}

int main (int argc, char *argv[])
{
  printf ("g_error=%d\n", g_error);
  g_error |= foo ();
  printf ("g_error=%d\n", g_error);

  return 0;
}

does print 0 + 1 (both tests without optimizations on gcc 4.3.2 fc10 i386)

So, here, the C and C++ frontends do not agree on when g_error is read
relative to the call to foo. Is this expected (i.e., is this a bug in
one of them) ?

If this is expected, are there recommendations about how this kind of
code should be written to avoid such un-expected differing behaviors ?
(Yes, it's pretty trivial to store the return value of foo and then to
or it separately, but I wonder what is the best way to make sure that
this kind of error creeps in).

Mathieu
-- 
Mathieu Lacage <mathieu.lacage@gmail.com>



More information about the Gcc-help mailing list