Fooling a c++ compiler. Passing int instead of a cont int into function

后端 未结 2 510
陌清茗
陌清茗 2021-01-29 16:14

How can i pass an int into a function that is expecting a const int.

Or is there a way of modifying cont int value?

Edit: I Sho

相关标签:
2条回答
  • 2021-01-29 16:54

    A top level const in a function parameter list is completely ignored, so

    void foo(const int n);
    

    is exactly the same as

    void foo(int n);
    

    So, you just pass an int.

    The only difference is in the function definition, in which n is const in the first example, and mutable in the second. So this particular const can be seen as an implementation detail and should be avoided in a function declaration. For example, here we don't want to modify n inside of the function:

    void foo(int n); // function declaration. No const, it wouldn't matter and might give the wrong impression
    
    void foo(const int n) 
    {
      // implementation chooses not to modify n, the caller shouldn't care.
    }
    
    0 讨论(0)
  • 2021-01-29 16:59

    This requires no fooling. A function that expects an argument of type const int will happily accept an argument of type int.

    The following code will work fine:

    void MyFunction(const int value);
    
    int foo = 5;
    MyFunction(foo);
    

    Because the argument is passed by value, the const is really rather meaningless. The only effect is has is to ensure that the function's local copy of the variable is not modified. The variable you pass to the function will never be modified, regardless of whether the argument is taken as const or not.

    0 讨论(0)
提交回复
热议问题