caramel1995
caramel1995

Reputation: 3055

Why can't C constant be stored in short type

As the title implies, I don't understand why it is like that.

The Code:

#include <stdio.h>
#define try 32


int main(void)
{

    printf("%ld\n" , sizeof try);

    return 0;

}

The Question:

1.) When I try using sizeof operator to get the size of storage the constant try is stored in, I get 4 which is 32-bits.

2.) Why doesn't C store it in 16-bits short since it is large enough to hold it.

3.) Is there any ways to make a constant be stored in short type?

Thank you for reading my question, Much appreciated.

Upvotes: 0

Views: 676

Answers (4)

greydet
greydet

Reputation: 5539

What you call a constant definition is in fact a macro definition that says the label try will be replaced by 32 at preprocessing time.

So the compiler will understand it sizeof(32) which does not have any type specified. So it gets the default types which is system dependent.

To make a short constant you will have either to cast your value in the defined macro or initialize it as a global one like follow:

const short try = 32;

Upvotes: 1

cost
cost

Reputation: 4480

I will take a crack at this, but I'm not entirely sure if I'm correct

Since #define is just telling the preprocessor to replace try with your number, it's acting as if it was just a value. On your specific machine, that value is being stored in a 4 byte space in memory. The only solution to this I can think of is to use a machine with an architecture that uses a default 16 bit size for an int.

Even if it was a short, it might still occupy 4 bytes in memory because of alignment, but it really depends.

Upvotes: 0

nobody
nobody

Reputation: 20174

You misunderstand the C preprocessor. The C preprocessor simply performs string substitution - it has no knowledge of types. The '32' will get interpreted according to the language rules applying to the context where it gets inserted - typically, as an int.

To make your defined value always be seen as a short, you could do:

#define try ((short)32)

See also: How do I write a short literal in C++?

Upvotes: 3

mduvall
mduvall

Reputation: 1038

Declared constants are probably what you are looking for:

const short try = 32;

This is typically preferred as I believe without optimizations (or maybe even with) the compiler will not try to fit any data type into the smallest number of addressable bytes.

Upvotes: 2

Related Questions