Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Constants

Tags:

c

If I declare a constant say #define MONTHS =12 in C, I am aware that pre-processor directive will replace whereever MONTHS is used, but I want to know if a memory is allocated to store 12

If yes, what would be the label and what would be the datatype?

like image 402
Lakshmi Avatar asked Nov 27 '22 22:11

Lakshmi


1 Answers

You most likely want your define as such:

#define MONTHS 12

/* some code here... */

int payAnnual = payMonthly * MONTHS;

To answer your question, no memory will be used. The pre-processor is unaware of such concepts as variables and memory. It is essentially an automated text editor. It will replace any occurrence of the symbol MONTHS with 12.

Since the pre-processor is so dumb, it is generally preferable to use a const variable. This gives you the benefit of type-checking, and can make compiler errors easier to read. And so long as you declare it static, the variable will be optimized away. (If you don't declare a global variable static in C, by default, it will be exported, so the compiler can't optimize it away entirely.)

static const int MONTHS = 12;
like image 172
Conspicuous Compiler Avatar answered Nov 29 '22 11:11

Conspicuous Compiler