C++ “const” keyword explanation

前端 未结 8 1944
半阙折子戏
半阙折子戏 2020-12-24 12:58

When reading tutorials and code written in C++, I often stumble over the const keyword.

I see that it is used like the following:

const          


        
8条回答
  •  遥遥无期
    2020-12-24 13:11

    The const qualifier means that a variable/pointer defined as const may not be changed by your program and it will receive its value either from an explicit initialization or by a hardware-dependent means.

    A pointer that is defined as const in the parameter declarations, the function code will not modify what it points to. Basically, you can use the pointer and it pretty much functions as a "read-only".

    For example:-

    void foo(const char *x)
    {
        while(*x)
        {
            if(*x==' ') cout << '-'; //printing - when a space is encountered
            else cout << *x;
            x++;
        }
    }
    

    The above function is fine and won't show any errors. But if foo had any thing that could change the string passed. say a function that replaces spaces with $. Not print $ but changing it to $. Something like this:-

    void foo(const char *x)
    {
        while(*x)
        {
            if(*x==' ') *x = '$'; //printing - when a space is encountered
            else cout << *x;
            x++;
        }
    }
    

    then it would not compile i.e. an assignment error to a read-only memory location.

提交回复
热议问题