C Programming – Why Some Functions Have an Underscore Prefix

c++functionnetworkingsockets

I recently started learning networking in C and I saw some functions that start with an underscore- like _function()- what does that mean exactly? I also saw this :

 struct sockaddr_in  {  

__SOCKADDR_COMMON (sin_);  

 in_port_t sin_port;    

 struct in_addr sin_addr;    

 unsigned char sin_zero[sizeof (struct sockaddr) - 

 __SOCKADDR_COMMON_SIZE -  

sizeof (in_port_t) -         

sizeof (struct in_addr)];  

};

what does this parts of the code mean:

__SOCKADDR_COMMON (sin_);

unsigned char sin_zero[sizeof (struct sockaddr) - 

 __SOCKADDR_COMMON_SIZE -  

sizeof (in_port_t) -         

sizeof (struct in_addr)];

Best Answer

The underscore prefix is reserved for functions and types used by the compiler and standard library. The standard library can use these names freely because they will never conflict with correct user programs.

The other side to this is that you are not allowed to define names that begin with an underscore.

Well, that is the gist of the rule. The actual rule is this:

  • You cannot define any identifiers in global scope whose names begin with an underscore, because these may conflict with hidden (private) library definitions. So this is invalid in your code:

    #ifndef _my_header_h_
    #define _my_header_h_ // wrong
    int _x; // wrong
    float _my_function(void); // wrong
    #endif
    

    But this is valid:

    #ifndef my_header_h
    #define my_header_h // ok
    int x; // ok
    float my_function(void) { // ok
        int _x = 3; // ok in function
    }
    struct my_struct {
        int _x; // ok inside structure
    };
    #endif
    
  • You cannot define any identifiers in any scope whose names begin with two underscores, or one underscore followed by a capital letter. So this is invalid:

    struct my_struct {
        int _Field; // Wrong!
        int __field; // Wrong!
    };
    void my_function(void) {
        int _X; // Wrong!
        int __y; // Wrong!
    }
    

    But this is okay:

    struct my_struct {
        int _field; // okay
    };
    void my_function(void) {
        int _x; // okay
    }
    

There are actually a few more rules, just to make things complicated, but the ones above are the most often violated and the easiest to remember.

Related Question