Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When you define a value in C how does the compiler select the data type

Tags:

c++

c

types

Just a general question about programming: When you define a value in C (or any language I suppose), How does the compiler known how to treat the value? For example:

#define CountCycle  100000

I would assume CountCycle is a "long integer" data type, but that's just an assumption. I suppose it could also be a float, a double (not an int as it maxes out at ~32k), etc.

How does the compiler choose the data type for a #define value? I have no application for the answer to this question; I'm just curious.

like image 361
Diesel Avatar asked Aug 31 '17 13:08

Diesel


2 Answers

The compiler does no such thing. The preprocessor substitues 100000 for CountCycle.

Once that substitution has been completed, the compiler can take over. 100000 has the type int if it can fit in that range, a long if it can't.

See a C++ Reference and a C Reference.

like image 98
Bathsheba Avatar answered Oct 04 '22 03:10

Bathsheba


CountCycle does not have a type. It can be substituted for the integer constant 100000 by the preprocessor everywhere in the program where this name is encountered.

It is the integer constant 100000 that has a type.

If an integer decimal constant does not have a suffix then (The C Standard, 6.4.4.1 Integer constants)

5 The type of an integer constant is the first of the corresponding list in which its value can be represented.

int
long int
long long int

If you want that the constant had the type long int you could specify a suffix. For example

#define CountCycle  100000l

if the value of the constant is in the domain of the type long int then the constant will have the type. Otherwise it will have type long long int.

If you want to specify a floating constant you should use one of its representations. For example

#define CountCycle  100000.0
like image 43
Vlad from Moscow Avatar answered Oct 04 '22 05:10

Vlad from Moscow