user4776812
user4776812

Reputation:

Usage const modifier in function

From the linux kernel scripts/mod/modpost.c:

static int is_vmlinux(const char *modname)
{
    const char *myname;

    myname = strrchr(modname, '/');
    if (myname)
            myname++;
    else
            myname = modname;

    return (strcmp(myname, "vmlinux") == 0) ||
           (strcmp(myname, "vmlinux.o") == 0);
}

How I understand:

This is defining the pointer to type of char and the const modifier. This pointer cannot be changed. But on the next lines we change the pointer.

Is it correct? Looks like no. :(

Why in this code use const? What doing here const? Can we write it without const?

Upvotes: 2

Views: 252

Answers (1)

const char * myname;

is a pointer to constant (content). You are allowed to modify the pointer. e.g. myname = NULL, myname++, but modification of the content is not possible.

char * const myname;

is a constant pointer. The opposite is possible. You are not allowed to modify the pointer, but you are allowed to modify what it points to e.g. *myname ^= ' ', which makes letter upper case if it is lower case.

Upvotes: 6

Related Questions