Shubhashish
Shubhashish

Reputation: 64

Different compilers showing different results for sizeof() operator

#include<stdio.h>
int main(void)
{
    unsigned const* const a, b;
    printf("size of a: %ld, size of b: %ld ", sizeof(a), sizeof(b));
    return 0;
}

This code gives different outputs on different compilers. In gcc compiler, the output is:

"size of a: 8, size of b: 4

In MSVS 2019 compiler and MinGW compiler, the output is

"size of a: 4, size of b: 4

I am looking for an explanation behind this behavior.

Edit:

Do a and b have different variable types here?

Upvotes: 1

Views: 310

Answers (3)

John Bode
John Bode

Reputation: 123458

The declaration

unsigned const* const a, b;

is parsed as

unsigned const (* const a), b;

Thus, a and b have different types - a is a const pointer to const unsigned int, while b is just a const unsigned int.

This is an aspect of C declaration syntax that isn't well-taught and constantly trips people up. Declarations are split into two main parts - a sequence of declaration specifiers and a sequence of declarators. Pointer-ness, array-ness, and function-ness are specified as part of the declarator. For array and function declarators it's obvious because the [] and () operators are postfix, but for pointers it's confusing because a) the * operator is unary, not postfix, and b) whitespace isn't meaningful - T *p and T* p are both interpreted the same way, as T (*p).

For the declaration above, the declaration specifiers are unsigned const and the declarators are * const a and b.

C does not specify exact sizes for most types - instead, it specifies a minimum range of values those types must be able to represent. An unsigned int must be able to represent values in at least the range [0..65535], meaning it must be at least 16 bits wide, but it may be wider. Pointer types are as big as the architecture needs them to be, typically 8 bytes on a 64-bit system.

Upvotes: 2

Amir Amirov
Amir Amirov

Reputation: 13

Although, 4 bytes integer size is typical, it is not guaranteed. In particular, sizes depend on the hardware and the compiler. The int size in different compilers can be either 2 bytes or 4 bytes.

Upvotes: 0

0___________
0___________

Reputation: 67476

On 32 bit program pointers are 32 bit long == 4 bytes. 64 bits build will have 64 bits long pointers - thus 8 bytes.

sizeof of int is minimum 2 bytes - usually 4.

But even the same compiler can give you different numbers (if compiling 32 or 64 bits program):

enter image description here

https://godbolt.org/z/a45MPa

Upvotes: 1

Related Questions