0

I've got message warning C4090: '=': different 'const' qualifiers when compiling my C program.

I've seen some info here, here and even here. But I still don't understand how are they related with my problem. For compiling I use Visual C++ 2015 x64 Native Build Tools Command Prompt. I know that it's because of using const in function declaration. But array is not changing. So what's the deal?

Here is my code:

#include <stdio.h>

int sum_array(const int a[], int n)
{
    int *p, sum;

    sum = 0;
    for (p = a; p < a + n; p++)
        sum += *p;

    return sum;
}

int main(void)
{
    int a[5] = {1, 2, 3, 4, 5};
    printf("%d", sum_array(a, 5));
    return 0;
}

Program works well, I just want to understand why I get this warning.

Petr
  • 420
  • 3
  • 13
  • 1
    Side note: You can write sum_array(a, sizeof(a) / size(*a)); You don't have to count the number of elements yourself and hard code it. – machine_1 Mar 31 '19 at 23:22

1 Answers1

2

I'm surprised it is only a warning. In C++ this would be entirely ill-formed.

Your function takes a const int*, which you then assign to an int*.

That is not const-correct.

I guess you meant const int *p??

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055