1

I've got a problem when the function is called by other functions.

My functions are so:

void *table_lookup(const table *t) {
    ...
    //Here I want to call my other function. 
    table_remove(t);
    ...
}

void table_remove(table *t) {
    ...
}

I got a warning when I compile it. The problem is that I cannot change the argument's type.

chqrlie
  • 131,814
  • 10
  • 121
  • 189

5 Answers5

1

You must NOT cast away the const qualifier. Any attempt to thereafter modify the value that was qualified const invokes Undefined Behavior. See C11 Standard - 6.7.3 Type qualifiers(p6).

The table_lookup parameter is const qualified for a reason. It allows the compiler to optimize the use of t. If you cast away the const and attempt to modify t you are breaking your promise to the compiler that t won't be modified.

Instead, you should refactor your code so that the remove() function calls table_lookup inside it to obtain a pointer (presumably) to the node you wish to remove. Then remove the node. Don't try and add a remove() within table_lookup. Create a new function.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
0

In C, you can directly cast it to remove the 'const' property.

void *table_lookup(const table *t)
//Here I want to call my other function. 
table_remove((table*)t)   // remove 'const' by directly casting.
...
return

void table_remove(table *t)
...
Yuanhui
  • 459
  • 5
  • 15
  • 1
    If you directly cast a `const table *t` as `(table *)t` and then modify `t` you are screwed (likely SegFault). It is bad practice leading to undefined behavior to attempt to cast away the `const` qualifier. – David C. Rankin Mar 10 '19 at 06:54
0

You can cast away the const qualifier: table_remove((table *)t); but you might run into problems if table_remove tries to modify the table structure, for example if it is stored in a read-only segment.

Therefore you should not do it. It is rather unexpected that a lookup function would modify the table anyway. If it does for good reasons, such as building a hash table or maintaining a cache, the argument should not be declared as const.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
0

Yes That’s right. it was bad idea to cast away const qualifier. . I can’t add a new function either. ((table)*) gives problem.

0

You can try the code below:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
void *table_lookup(const table *t) {
    table_remove((table *)t);
}
#pragma GCC diagnostic pop

From: https://stackoverflow.com/a/13253997/5093308

Zhou Hongbo
  • 1,297
  • 13
  • 25