I prefer to add const
modifier to all built-in arguments in functions I write. E.g.:
void foo(const int arg1, const double arg2);
is better for me than:
void foo(int arg1, double arg2);
After code review I was told that const
modifier brings an overhead when it is applied for integer and built-in types. Is that true and why?
Thanks,
It has no more overhead than a typedef
does. Your coworker is wrong.
If you want to convince him, print out the disassembly of both variants, and show your coworker that they're the same.
However, adding the const
qualifier to primitive types like this is utterly pointless and futile. They're copied anyway, and there's no harm in modifying them. There's nothing to be gained by making them const.
There's no overhead with const
, I guess your coworkers are just confused with the use as it is (unfortunately) not so common. Personally I prefer to const
as many local variables as possible since it increases readability.
Of course it's always easy to disprove, take the following program and compile with assembly output:
#include <stdio.h>
void foo1(int a, double b)
{
printf("Not const %d, %g\n", a, b);
}
void foo2(const int a, const double b)
{
printf("Const %d, %g\n", a, b);
}
int main()
{
for(int i = 0; i < 10; ++i)
{
foo1(i, 5.5 * i);
foo2(i, 12.8 * i);
}
return 0;
}
The assembly code generated for those functions is exactly the same (using VS2010 release-build):
For foo1
(without const
-specifiers):
; 4 : {
push ebp
mov ebp, esp
; 5 : printf("Not const %d, %g\n", a, b);
fld QWORD PTR _b$[ebp]
sub esp, 8
fstp QWORD PTR [esp]
push eax
push OFFSET ??_C@_0BC@FACFPKBC@Not?5const?5?$CFd?0?5?$CFg?6?$AA@
call DWORD PTR __imp__printf
add esp, 16 ; 00000010H
; 6 : }
For foo2
(with const
-specifiers):
; 9 : {
push ebp
mov ebp, esp
; 10 : printf("Const %d, %g\n", a, b);
fld QWORD PTR _b$[ebp]
sub esp, 8
fstp QWORD PTR [esp]
push eax
push OFFSET ??_C@_0O@LOLEPDHC@Const?5?$CFd?0?5?$CFg?6?$AA@
call DWORD PTR __imp__printf
add esp, 16 ; 00000010H
; 11 : }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With