Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit cast when assigning pointers in C

In C if I write the following code:

#include <stdio.h>

int main() {
        char c;    
        int* ip;
        char* cp;

        cp = &c;
        ip = cp;

        printf("%p %p %p %p\n", cp, ip, cp+1, ip+1);

        return 0;
}

I get a warning about not explicitly casting cp to ip. However, the code itself seems to work just fine. If c had address 1000 I get 1000 1000 1001 1004 as output.

My question is why is the explicit cast needed. Is it simply because the C standard doesn't state anything about implicit conversions of pointers (other than void*) or is there something else going on in the explicit cast?

like image 219
Samik Avatar asked Jul 12 '26 19:07

Samik


1 Answers

I get a warning about not explicitly casting cp to ip.

You aren't compiling with strict enough compiler settings then. If you wish to get an error upon C language violations, you'll need something like gcc -std=c11 -pedantic-errors or equivalent.

However, the code itself seems to work just fine.

char* and int* are not compatible pointer types. Your code is not fine as far as the C language is concerned - ip = cp; is a violation of the "simple assignment" rule. And so your code relies on undefined behavior and non-standard compiler extensions.

My question is why is the explicit cast needed. Is it simply because the C standard doesn't state anything about implicit conversions of pointers (other than void*) or is there something else going on in the explicit cast?

Specifically, because of the rules of how to use the assignment operator, stated at C17 6.5.16.1 Simple assignment, emphasis mine:

One of the following shall hold:
/--/
- the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;

The same rule has exceptions for void* and null pointer constants.

like image 58
Lundin Avatar answered Jul 15 '26 10:07

Lundin