Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do both "std::printf" and "printf" compile when using <cstdio> rather than <stdio.h> in C++? [duplicate]

To my knowledge, headers of the form cxyz are identical to xyz.h with the only difference being that cxyz places all of the contents of xyz.h under the namespace std. Why is it that the following programs both compile on GCC 4.9 and clang 6.0?

#include <cstdio>

int main() {
    printf("Testing...");
    return 0;
}

and the second program:

#include <cstdio>

int main() {
    std::printf("Testing...");
    return 0;
}

The same goes for the FILE struct:

FILE* test = fopen("test.txt", "w");

and

std::FILE* test = std::fopen("test.txt", "w");

both work.

Up until now, I always thought that it was better to use cstdio, cstring, etc, rather than their non-namespaced counterparts. However, which of the following two programs above are better practice?

The same goes for other C functions such as memset (from cstring), scanf (also from cstdio), etc.

(I know some people will ask why I am using C IO in a C++ program; the issue here is not specifically C IO, but whether or not this code should compile without specifically specifying std:: before calling a namespaced C function.)

like image 301
ra1nmaster Avatar asked Mar 18 '23 05:03

ra1nmaster


1 Answers

The standard permits the compiler to also inject the names into the global namespace.

One reason for this is that it permits the implementation of <cstdio> to be:

#include <stdio.h>

namespace std
{
    using ::printf;
    using ::fopen;
    // etc.
}

so the compiler/library vendor does not have to write and maintain so much code.

In your own code, always use std:: or using namespace std; etc. so that your code is portable to compilers which do not inject the names into global namespace.

like image 126
M.M Avatar answered Apr 07 '23 17:04

M.M