How to pass “literal” integers by reference in C++

You cannot bind a literal to an lvalue reference to non-const (because modifying the value of a literal is not an operation that makes sense). You can however bind a literal to a reference to const.

So this will compile if you declare fillRect as:

void fillRect(int const& x, int const& y, int const& width, int const& height)

In this case you are passing ints. ints are so cheap to copy that passing by them by reference will probably make the performance of your program worse.

The function fillRect is probably so expensive that the cost of passing its arguments is totally irrelevant in any case. Or maybe it will be inlined, and there will be no cost whatsoever to passing the arguments. These sorts of micro-optimisations are usually not optimisations at all, and should always be guided by the results of profiling (if they are done at all).

Leave a Comment