Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Know if const qualifier is used

Tags:

c

constants

Is there any way in C to find if a variable has the const qualifier? Or if it's stored in the .rodata section?

For example, if I have this function:

void foo(char* myString) {...}

different actions should be taken in these two different function calls:

char str[] = "abc";
foo(str);

foo("def");

In the first case I can modify the string, in the second one no.

like image 550
Dario Avatar asked Dec 27 '22 11:12

Dario


2 Answers

Not in standard C, i.e. not portably.

myString is just a char* in foo, all other information is lost. Whatever you feed into the function is automatically converted to char*.

And C does not know about ".rodata".

Depending on your platform you could check the address in myString (if you know your address ranges).

like image 186
undur_gongor Avatar answered Jan 09 '23 20:01

undur_gongor


You can't differ them using the language alone. In other words, this is not possible without recurring to features specific to the compiler you're using, which is likely not to be portable. A few important remarks though:

In the first case you COULD modify the string, but you MUST NOT. If you want a mutable string, use initialization instead of assignment.

char *str1 = "abc"; // NOT OK, should be const char *
const char *str2 = "abc"; // OK, but not mutable
char str3[] = "abc"; // OK, using initialization, you can change its contents
like image 40
jweyrich Avatar answered Jan 09 '23 22:01

jweyrich