Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are "long *" and "int *" not compatible in 32-bit code?

Tags:

c++

c

I was wondering why the following code doesn't compile:

void foo_int(int *a) { }
void foo_long(long *a) { }

int main()
{
    int i;
    long l;

    foo_long(&i);
    foo_int(&l);
}

I am using GCC, and neither calls work either in C or C++. Since it is a 32-bit system, both int and long are signed 32-bit integers (which can be verified with sizeof at compile time).

The reason I am asking is that I have two separate header files, neither are under my control, and one does something like: typedef unsigned long u32; and the other: typedef unsigned int uint32_t;. The declarations are basically compatible, except when I use them as pointers as in the above code snippet, I have to explicitly cast.

Any idea why this is?

like image 647
Greg Rogers Avatar asked Sep 22 '09 17:09

Greg Rogers


People also ask

Can a'int be of 32 bits?

In 32-bit operating systems, the int type is usually 32 bits, or 4 bytes. Thus, the int type is equivalent to either the short int or the long int type, and the unsigned int type is equivalent to either the unsigned short or the unsigned long type, depending on the target environment.

Is long int 32-bit?

int , long , ptr , and off_t are all 32 bits (4 bytes) in size. int is 32 bits in size.


1 Answers

Just because long and int both happen to be 32-bit on your particular compiler and hardware, does not mean that they will always both be 32-bit on every kind of hardware and every compiler.

C (and C++) were designed to be source-portable between different compilers and different hardware.

like image 108
system PAUSE Avatar answered Oct 05 '22 09:10

system PAUSE