SoftOver
 
Recommended


User login


 

Unformation

   

Is this code valid? Why? What will be printed?

#include <stdio.h>

class C
{
  int n_;
  const char * s_;
public:
  C (const char * s) : n_(0),s_(s) {}
  operator const char * () { return s_; }
  operator int() { ++n_; return n_; }
};

int main()
{
  C c("Unformat %s %d\n");
  printf(c,c,c);
}

Explanation:

The code is valid, but the behavior is undefined. printf signature is int printf(const char * format [ , argument , ...] );, and only first argument has defined type. It means that only first c in printf(c,c,c) is converted, other two are passed as is, and then treated by printf as a string and an integer. The results are compiler- and platform-dependent, and even not all compilers will warn you. The results vary from Unformat (null) [some number] to system exception / segfault.

ALERT! Guideline: Avoid varargs. If you have a good reason (e.g. proved performance problems) to use them - clearly understand what are you doing.