2

I wanna use C libraries such as cstdio and cstdlib, and I can use both:

int i = atoi("123");

or

int i = std::atoi("123");

Both work fine. Which one should I use? Are they equivalent?

SwiftMango
  • 15,092
  • 13
  • 71
  • 136
  • Well, `std::atoi` is the C++ standard `atoi`, so why still use the non-standard one? – Mark Garcia Feb 24 '14 at 05:17
  • possible duplicate of [cstdio stdio.h namespace](http://stackoverflow.com/questions/10460250/cstdio-stdio-h-namespace) –  Feb 24 '14 at 05:18
  • I think it depends on your optimization level too. If you’re able to compile your code at O2 or above, there’s almost no difference between the two methods. If you have to use O0 or O1, you’re best to use `atoi` only – P0W Feb 24 '14 at 05:21
  • 4
    @P0W: What does optimisation have to do with anything? It's the same function, accessed via different names. Names are resolved at compile time, regardless of optimisation. – Mike Seymour Feb 24 '14 at 05:33

1 Answers1

7

For portability, you should use the std versions, for two reasons:

  • The standard doesn't guarantee that C library functions are dumped into the global namespace; it just allows implementations to do that. This means your code might not compile if you change implementations.
  • Some functions (not atoi, but mathematical functions, for example) have extra overloads in C++. At least one popular library dumps the C overload into the global namespace, but not the C++ overloads. This means your code might change its behaviour in bizarre and infuriating ways if you change implementations.
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644