'const' with double indirection

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi all!

I'm not sure if the following is a compiler issue or a language/standard
misunderstandig my side.
(And I hope that in general this all is understood, English is not my native
language.)

See the example C code at the end of the message for details:

First case, all identifiers are postfixed with a '1':
I want to pass a variable by double indirection to 2 nested functions.
The outer function is supposed to modify the variable (and not both
pointers).
The inner function is supposed not to modify the variable, so all is
'const'.

Why is the compiler is issueing a warning when the call of the inner
function is made?

In contrast to case '1', have made case '2':
This is the same as case '1', except one pointer is not 'const'.
Now it is correct that the compiler issues a warning when calling the inner
function.
To illustrate why case '2' has a correct warning I added some
constants/variables and assignments.
When compiled and runned, the program crashed at the line marked with /*
Oops! */.
This is in my opion a correct 'crash', so the warning is correct issued.

But for case '1', I can't write illegal code, so why is the warning issued?

I'v tried it both on GCC 2.96 and GCC 4.1.1 with the same result:
a warning for both cases.

I'v tried a Borland Win32 compiler (command line v5.5):
only a warning for case '2'.
(Detail: the program don't crash, by does the assignment after the call to
g2 with disastrous result.)

I'v tried the MicroSoft Visual C++ 6 compiler:
No warnings at all, but it crashes at the same place.

Any one an idea?

Jacob

--- const.c ---

#include <stdio.h>

const int c = 0;
const int *c1 = &c;
const int *c2 = &c;

void g1(const int * const * const List) {
/*  error: assignment of read-only location
    *List = c1; */
}   /* g1 */

void f1(int * const * const List) {
    **List = 1;
    g1(List);
    **List = 11;
}   /* f1 */

void g2(const int ** const List) {
    *List = c2;
}   /* g2 */

void f2(int ** const List) {
    **List = 2;
    g2(List);
    **List = 22; /* Oops! */
}   /* f2 */

int A1[2] = { 3, 4 };
int A2[2] = { 5, 6 };
int * const List1[2] = { &A1[0], &A1[1] } ;
int *       List2[2] = { &A2[0], &A2[1] } ;

int main(void) {
    printf("c:%d, A1[0]:%d, A1[1]:%d, A2[0]:%d, A2[1]:%d\n", c, A1[0],
A1[1], A2[0], A2[1]);
    f1(List1);
    f2(List2);
    printf("c:%d, A1[0]:%d, A1[1]:%d, A2[0]:%d, A2[1]:%d\n", c, A1[0],
A1[1], A2[0], A2[1]);
    return 0;
}



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux