Home  >  Article  >  Backend Development  >  Why Does `printf` Work Without `std::` in C When `cstdio` is Included?

Why Does `printf` Work Without `std::` in C When `cstdio` is Included?

DDD
DDDOriginal
2024-10-26 01:13:02695browse

 Why Does `printf` Work Without `std::` in C   When `cstdio` is Included?

cstdio stdio.h Namespace

The C reference for cstdio states that "Every element of the library is defined within the std namespace." However, you found that both std::printf and printf work, raising the question of whether C headers include symbols in both namespaces.

The answer is more nuanced.

Including cstdio

Including cstdio imports symbols into the std namespace and possibly into the global namespace. This is because cstdio includes stdio.h, which is a C-style header.

Including stdio.h

Including stdio.h imports symbols into the global namespace and possibly into the std namespace. This is because stdio.h is a C-style header.

Compatibility Features

The use of C-style headers in C is a compatibility feature. The C 11 standard specifies that for compatibility with the C standard library, the C standard library provides 25 C headers, including cstdio and stdio.h.

The standard further states that each C header "behaves as if each name placed in the standard library namespace by the corresponding cname header is placed within the global namespace scope."

Conclusion

In summary, when including C-style headers in C , symbols may be imported into both the std and global namespaces, depending on the specific headers being used and the implementation of the compiler. However, it is not always guaranteed that both namespaces will contain the same symbols.

The above is the detailed content of Why Does `printf` Work Without `std::` in C When `cstdio` is Included?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn