Weird C function declaration

心已入冬 提交于 2019-12-06 07:05:50

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/33816001/weird-c-function-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!