Roberto Rocco
Roberto Rocco

Reputation: 450

Why does const not work even if the variable is not changed?

I'm trying to protect the -a- array of the my_sum_array function from the changes. In the function block I do not make any changes to -a-, but I have a warning (warning: assignment to 'int *' from 'const int *' discards the qualifiers [-Wincompatible-pointer-types-discards-qualifiers]). I know I could remove const to make the program work, but I would like to understand if something is missing from me.

#include <stdio.h>

#define MAX 5

int my_sum_array(const int a[], int n);

int main(void) {
    int values[5] = {4, 7, 1, 7, 8};

    printf("The sum in my_sum_array is :%d\n", my_sum_array(values, MAX));

    return 0;
}

int my_sum_array(const int a[], int n) {
    int *p, sum = 0;

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

    return sum;
}

Upvotes: 0

Views: 97

Answers (3)

Blastfurnace
Blastfurnace

Reputation: 18652

The warning is caused by the assignment p = a in the for loop. The variable is defined as int *p, a pointer to non-const int. The warning is correct, "assignment to int * from const int * discards the qualifiers". It's as though you've casted away the constness of the a pointer parameter.

I'd change your function to:

int my_sum_array(const int a[], int n) {
    int sum = 0;

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

    return sum;
}

This defines p as a pointer-to-const, just like a, and also limits its lifetime to the for loop.

Upvotes: 2

smac89
smac89

Reputation: 43078

Change type of p to:

const int *p;

So now you end up with:

const int * p;
int sum = 0;

Upvotes: 0

Abdelhak Bougouffa
Abdelhak Bougouffa

Reputation: 86

Make your p pointer as:

    int const * p;

i.e.

here, p is a pointer to a const integer

Upvotes: 1

Related Questions