Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using standard C functions in C++, is the "std::" prefix required? [duplicate]

Tags:

c++

c

When use standard C function in C++, should we prefix every function with std::?

for example (file name: std.C):

#include <cstdio>

int main() {
  std::printf("hello\n");
  printf("hello\n");
}

This file can be compiled with:

g++ -Wall -Werror -std=c++11 std.C

without any error.

my questions are:

  1. Should we always place std:: before all the standard C library functions when they are used in C++?
  2. What's the main difference between header files like <stdio.h> and <cstdio>?
like image 453
Yishu Fang Avatar asked Apr 27 '15 13:04

Yishu Fang


People also ask

What is std in C language?

Explanation: It is known that “std” (abbreviation for the standard) is a namespace whose members are used in the program. So the members of the “std” namespace are cout, cin, endl, etc. This namespace is present in the iostream. h header file.

Does C use STD?

All C++ standard library names, including the C library names, if you include them, are defined in the namespace std . This means that you must qualify all the library names using one of the following methods: Specify the standard namespace, for example: std::printf("example\n");

What is std :: in C ++?

std::source_location is a class first introduced in C++20 that represents certain information about the source code, such as file names, line numbers, and function names.

What is the C standard?

What is the C programming language standard? It is the standard way defined for the compiler creators about the compilation of the code. The latest C standard was released in June 2018 which is ISO/IEC 9899:2018 also known as the C11.


1 Answers

The C++ library includes the same definitions as the C language library organized in the same structure of header files, with the following differences:

  • Each header file has the same name as the C language version but with a "c" prefix and no extension. For example, the C++ equivalent for the C language header file <stdlib.h> is <cstdlib>.
  • Every element of the library is defined within the std namespace.

Nevertheless, for compatibility with C, the traditional header names name.h (like stdlib.h) are also provided with the same definitions within the global namespace although its use is deprecated in C++.

(source)

The std:: part of the std::printf() call is the standard way to use names in the standard library, therefore, I suggest to use it.

like image 67
Alper Avatar answered Sep 25 '22 20:09

Alper