June 2000 Obfuscated C++

Last Month's Obfuscated C++
What does this program print? How does the fact that f is inline affect the answer?


#include <iostream>
using namespace std;

static inline int f() {
  static int g = 0;
  return g++;
}

int main(){
  f();
  cout << f() << endl;
  return 0;
}
This program prints


1
g is a static, and therefore retains its values from one call to f to another. The fact that f is inline does not make a difference. The compiler must ensure that all of the expansions of the inline function share the same local static, even if the inline is called from multiple compilation units. This is one way that inline functions act very differently from macros.

This Month's Obfuscated C++
This month we look at namespaces. What does the following program print?


#include <iostream>
using namespace std;

namespace N {
  void g(int) { 
    cout << "g(int)\n"; 
  }
};

using N::g;

void r() {
  g('x');
}

namespace N {
  void g(char){ 
    cout << "g(char)\n"; 
  }
};

void s() {
  g('x');
}

using namespace N;

void t() {
  g('x');
}

int main(){
  r();
  s();
  t();
  return 0;
}

Rob Murray is Chief Technology Officer at the Irvine office of Nuforia, an object-oriented software consulting company based in Houston, TX. He has taught C++ at technical conferences since 1987 and is the author of C++ Strategies and Tactics. He was the founding editor of C++ Report and may be contacted at rmurray@nuforia.com.

Featured

Upcoming Events

AppTrends

Sign up for our newsletter.

I agree to this site's Privacy Policy.