Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const function in C

Tags:

c

function

In the source code of git, I saw the following function definition

const char *typename(unsigned int type)
{
    if (type >= ARRAY_SIZE(object_type_strings))
        return NULL;
    return object_type_strings[type];
}

I believed that typename is a function here, but seems be to a const function, which is very confusing to me.

What does this mean and how shall one use this const function feature?

link to source cod; https://github.com/git/git/blob/7d722536dd86b5fbd0c0434bfcea5588132ee6ad/object.c#L29

like image 496
Bob Avatar asked Dec 06 '25 10:12

Bob


1 Answers

Use cdecl

% cdecl
cdecl> explain const char *typename(unsigned int)
declare typename as function (unsigned int) returning pointer to const char

It is an useful tool sometimes, but it is quite restricted, for example it said

cdecl> explain const char *typename(unsigned int foo);
syntax error

But it is very useful when trying to make sense of function pointers:

cdecl> declare a as pointer to function (int, double, pointer to const char) 
       returning pointer to const volatile struct foo
const volatile struct foo *(*a)(int , double , const char *)

or

cdecl> explain const void *(*b[])(int , char (*(*)(char ))(double))
declare b as array of pointer to function (int, pointer to function (char) returning pointer
to function (double) returning char) returning pointer to const void
like image 164


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!