un-expected side-effect of function call

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

 



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@xxxxxxxxx>

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux