Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc error: invalid conversion from double* to const double

Tags:

c++

gcc

I'm using gcc version 4.5.0. Using the following simple example I would assume to get an error invalid conversion from double* to const double*

#include <iostream>
using namespace std;

void foo(const double *a)
{
    cout<<a[0]*2.<<endl;
}

int main()
{
    double *a=new double[2];
    a[0]=1.;
    a[1]=2.;
    foo(a);
    return 1;
}

Why is it compiling without errors?

A counterexample is the following one which is similar:

#include<iostream>
using namespace std;

void foo(const double **a)
{
cout<<a[0][0]*2.<<endl;
}


int main()
{
    double **a=new double*[2];
    a[0]=new double[2];
    a[1]=new double[2];
    a[0][0]=1.;
    foo(a);
    cout<<a[0][0]<<endl;
    return 1;
}

(Solution for the second example: define foo as foo(const double*const* a). Thanks to Jack Edmonds comment this explains the error message)

like image 259
pawel_winzig Avatar asked Oct 25 '11 14:10

pawel_winzig


1 Answers

Generally, you are allowed to implicitly make things "more constant" but not "less constant" in C and C++. Therefore, you are allowed to pass a non-const object to a function that takes a const object.

Basically the const parameter in the method declaration is the function's way of promising not to modify the parameter.

You can see this question for more information: Question about const_cast in c++

like image 147
Jack Edmonds Avatar answered Oct 13 '22 00:10

Jack Edmonds