Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison and assignment between pointer and integer C

Tags:

c

pointers

I've a theoretical question about these two statements:

Assuming p a pointer to an Integer and a an Integer:

a) if(p==a){.....} or if(p>a)..

b) p=a;

All of them are illegal and b is especially dangerous but how does standard C consider them?

Reading the standard, I haven't found if they are errors, undefined behaviors, unspecified behavior, constraint violation, if one of them is legal or other.

Looking in the countless similar question, I haven't found a solution.

like image 572
abc Avatar asked May 17 '12 17:05

abc


1 Answers

All are illegal. To perform comparison, both sides most be convertible to a common type, for assignment, the right-hand side must be convertible to the type of the left-hand side, and:

Conversions that involve pointers, other than where permitted by the constraints of 6.5.16.1, shall be specified by means of an explicit cast.

(6.5.4, 3; 6.5.16.1 describes some exceptions for the null pointer constant, void pointers and _Bool in the case of assignment.)

When you do add explicit casts to convert the pointers to integers, the program becomes valid again and you will get booleans from the comparisons. The results are implementation-dependent. Be sure to use uintptr_t when storing pointers in integers.

like image 57
Fred Foo Avatar answered Nov 15 '22 09:11

Fred Foo