Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overhead of const modifier for built-in types in C++

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,

like image 972
barankin Avatar asked Mar 19 '12 09:03

barankin


2 Answers

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.

like image 188
jalf Avatar answered Oct 13 '22 13:10

jalf


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   : }
like image 39
Andreas Magnusson Avatar answered Oct 13 '22 13:10

Andreas Magnusson