Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird C function declaration [duplicate]

I was going through some code when I encountered this in one of the source files.

int st_insert(table, key, value)
register st_table *table;
register st_data_t key;
st_data_t value;
{
    unsigned int hash_val, bin_pos;
    register st_table_entry *ptr;

    hash_val = do_hash(key, table);
    FIND_ENTRY(table, ptr, hash_val, bin_pos);

    if (ptr == 0) {
        ADD_DIRECT(table, key, value, hash_val, bin_pos);
        return 0;
    } else {
        ptr->record = value;
        return 1;
    }
}

What is this style? Is it some obscure way to declare functions? Is there some reason one might use this over normal function declarations?

like image 477
calccrypto Avatar asked Nov 19 '15 23:11

calccrypto


1 Answers

It is an old (but still valid according to the current C Standard) syntax of function definitions using an identifier list. The types of the identifies are declared after the identifier list and before the opening brace.

It is better to use functions with parameter type lists because in this case the compiler having a function prototype can check the correct list of arguments for a function call.

From the C Standard (6.9.1 Function definitions)

6 If the declarator includes an identifier list, each declaration in the declaration list shall have at least one declarator, those declarators shall declare only identifiers from the identifier list, and every identifier in the identifier list shall be declared. An identifier declared as a typedef name shall not be redeclared as a parameter. The declarations in the declaration list shall contain no storage-class specifier other than register and no initializations.

You can meet other funny constructions in old C code as for example this

memset( ( char * )p, value, n );
        ^^^^^^^^^^  

because type void was introduced later.

like image 79
Vlad from Moscow Avatar answered Nov 13 '22 06:11

Vlad from Moscow