Search code examples
c++integer

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


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 Should have mentioned this earlier, i am using ccs c compiler that is used to program pic microcontroller. fprintf function takes constant stream as its first argument. It will only accept a constant int and throw a compilation error otherwise "Stream must be a constant in the valid range.".

Edit 2: Stream is a constant byte.


Solution

  • 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.
    }