2

I have the following code

#include <iostream>
#include <cstdio>
volatile char s[7] = "test";
int main() {
   std::cout << s << std::endl;
   std::printf("%s\n", s);
}

It prints "1" with std::cout and "test" with std::printf. Why does it print "1" for the first case?! My system is "Linux debian 4.9.0-3-amd64 #1 SMP Debian 4.9.30-2+deb9u5 (2017-09-19) x86_64 GNU/Linux", my C++ compiler is "g++ (GCC) 7.3.0".

If I remove "volatile" keyword then std::cout prints the expected "test".

vollitwr
  • 429
  • 2
  • 8

1 Answers1

4

printf is variadic so takes any types of argument. cout is more strongly typed C++ thingie. A char const volatile* doesn't convert implicitly to char const*. But it converts to bool. Hence the 1.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • Can this be considered a bug is standard library? – Slava Apr 05 '18 at 14:56
  • I wouldn't call it a bug. But it's certainly unexpected behavior. Just like trying to output a wide string via `cout`, or a narrow non-ASCII string via `wcout` in Windows. – Cheers and hth. - Alf Apr 05 '18 at 14:56
  • I think standard library should have overload for volatile versions of `char *` and `void *` – Slava Apr 05 '18 at 14:58
  • I'm not entirely sure, what is the expected output for a string whose characters (which also means its length) can change while it's being printed? More in general, the common pattern in pretty much every library is to ignore `volatile` pointers; if the pointed object is "stable enough" to do something with it, the caller can confirm it by casting away the `volatile`. – Matteo Italia Apr 05 '18 at 15:12