This question already has answers here:
"static const" vs "#define" vs "enum"
(17 answers)
Why would someone use #define to define constants?
(9 answers)
Closed 8 years ago.
I would like to understand the difference between defining a constant variable as follows:
const int ONE = 1;
and using a preprocessor directive:
#define ONE (1)
I know that in the second case "1" gets in some sense hardcoded and the compiler does not even see the variable ONE, but I am not sure about the first case. The fact of declaring the variable as constant just prevents from accidentally change its value, or does the compiler catch the opportunity to do some optimization? Is there any significant benefit of one approach over the other?
In C, const int c; means that c can't be modified during the run of program. However, c is not a constant during compile time and can not be used in constant expressions. So for example the program:
const int MAX = 10;
int a[MAX];
does not compile, while:
#define MAX 10
int a[MAX];
does.
In C++, const variables are true compile-time constants, so there may be less reasons to use #define for it. An example where #define is necessary is when you need to use the constant in an #if directive.
Related
This question already has answers here:
Why use enum when #define is just as efficient? [duplicate]
(4 answers)
Closed 1 year ago.
I am a bit confused by what for and where enum is good? What are the benefits of using enum against defining global variables (constants) or macros? For instance in this code:
#include<stdio.h>
enum bool {false, true};
int main()
{
enum bool b = 100;
printf("%d", b);
return 0;
}
I can assign even any integer value to b and every thing works fine, so why not doing
int false = 0, true = 1;
or
#define false 0
#define true 1
in the global scope? Can some one explain where and why are enums useful and should be preferred to use?
There are many advantages to using enum over #define macros:
Advantage and disadvantages of #define vs. constants?
The use of an enumeration constant (enum) has many advantages over
using the traditional symbolic constant style of #define. These
advantages include a lower maintenance requirement, improved program
readability, and better debugging capability.
I would also encourage you to use bool (and <stdbool.h>) instead of an enum for true/false.
This question already has answers here:
variably modified array at file scope in C
(4 answers)
"static const" vs "#define" vs "enum"
(17 answers)
Defining the size of an array using a const int
(3 answers)
Closed 3 years ago.
int const a=9;
int stack[a];
int main()
{
return 0;
}
The above code gives an error:variably modified 'stack' at file scope
But when I change the code to :
#define b 3
int stack[b];
int main()
{
return 0;
}
It compiles without error.While both #define and const variable are used for defining the constant identifier then why there is error when I use the const var instead of #define.I searched the similar question but all they gave solution about the error but no reason to it.
Searched about the const and #define and found that sometimes gcc compiler recognizes const as readonly but it is too confusing.
In C language static storage variables can have size defined by the constant expression. Using the variable (even the constant one) as the size is not such a expression.
The error is 100 percent correct.
The second case: proprocessor replaces textually the b with 3 which is the constant expression
Constant expression is something which is evaluated during the compilation. Variable value can be only evaluated runtime.
This question already has answers here:
In C, why can't a const variable be used as an array size initializer? [duplicate]
(3 answers)
Closed 5 years ago.
I'm trying to create a struct with an array inside. The array size, I'm hoping, should be set at compile time. That is it's hard coded but uses a variable so I can change it easily in the code. Problem is I'm getting linker errors when I use const int in the header ahead of the struct definition. Here's my code:
from the header file:
const int t_Module_qInternalParams =64;
typedef struct Module{
double internalParams[t_Module_qInternalParams];
} t_Module;
This:
const int t_Module_qInternalParams = 64;
Is a constant in the sense that the object cannot be modified after initialization, but it's still a variable. Especially, t_Module_qInternalParams is not a compile-time constant, as required in your declarator.
A simple solution is to use a preprocessor macro instead:
#define MODULE_INTERNALPARAMS 64
This just expands to 64 before the compiling phase starts, and of course, 64 is a compile-time constant.
This question already has answers here:
Why can't I create an array with size determined by a global variable?
(8 answers)
Closed 8 years ago.
I declared a constant global variable 'MEM_PRIMES' and I wanna use it in the struct below as the array elements' number but it errors saying "variably modified 'primes' at file scope.
/* global data */
const unsigned int MEM_PRIMES = 100;
struct{
char *filename;
FILE *pfile;
int nrec;
unsigned long long primes[MEM_PRIMES];
size_t index;
}global = {"D:\\C\\C files\\mytext4.bin", NULL, 0, {2ULL, 3ULL, 5ULL}, 3};
const doesn't really ensure that the storage cannot be modified; you can take the address, cast away the const and modify it, so I believe that is why you get the complaint.
#define MEM_PRIMES 100
will fix it and is the C way.
You just can't do this in C, like you can in C++. You'll have to:
#define MEM_PRIMES 100
or similar.
The actual error message you're getting arises from the fact that you are allowed to have variable length arrays in C99 and later - you're just not allowed to have them at file scope (or in structs at all, for that matter) because the size would need to be determined at compile time. So rather than chewing you out for using a const int instead of an actual constant, your compiler is actually thinking you want a VLA, and telling you that you can't have one here.
As others have said, a const int variable is deemed to be a variable in C and cannot be used in contexts where a compile time constant is required, such dimensions of a global array or an array embedded in a structure (nor in a case clause within a switch, nor …).
While #define MEM_PRIMES 100 (suggested by the other answers) will work, I'd use:
enum { MEM_PRIMES = 100 };
The reasons are detailed in static const vs #define.
This question already has answers here:
"static const" vs "#define" vs "enum"
(17 answers)
What Is The Point of Symbolic Constants?
(5 answers)
Closed 9 years ago.
I don't see the need of using macro to define something , say in below example:
#define TELEPHONE 443 //why use this
int telephone = 443; //when same job is done by a regular variable
why would any one use macro for defining (declaring variable in C language) ? as in above scenario?
There are several cases when a macro is more appropriate. The top of my head are:
1.To define a constant:
#define PI 3.1415926
2.To use as a constant expression.
#define BUFSIZE 1024
later you can use
int buffer[BUFSIZE];
This job cannot be done even if you use const int bufsize = 1024; (without using variable length array)
EDIT:
To clarify the use of const from the comment, in this code:
int main()
{
const int x = 5;
int array[x];
return 0;
}
array is actually a variable length array, compile it with gcc test.c -std=c89 -pedantic, will generate the warning:
warning: ISO C90 forbids variable-size array `array'
The problem is, const variable in C isn't a constant expression, this is exactly my point of using #define in this situation. And this is one of the differences between C and C++.
Reference: C FAQ
Why would any one use macro for defining (declaring variable in C language) ?
The macro does not define a variable, it defines a constant. Your C program that uses TELEPHONE that's #defined is indistinguishable to the compiler from a program that contains the hard-coded value 443.
Unlike int telephone variable, the TELEPHONE macro cannot be changed at run-time, and does not have an address.
Finally, it is possible to provide values for macros on the command line when calling the compiler - something impossible to do when you are dealing with C variables. Instead of defining #define TELEPHONE 443 you could pass the value on the command line, like this:
gcc -DTELEPHONE=443 myprog.c
Using a variable takes up space in the final image, which may not be required or desired (e.g. in embedded applications), whereas a define is handled strictly by the compiler (preprocessor).
dasblinkenlight pretty much covers it but I would just clarify some things they say, macros don't really define constants, you do that with the const modifier, and you should be using that most of the time. A macro defines substitution text, the only thing it knows about the language you are writing in is its use of spaces. So for macros you can do stuff like this
#define CODE_SNIPPET 10; i++ ) printf( "Hello %d\n"
for( int i = 0; i < CODE_SNIPPET , i );
which before being passed to the parser would be convert by the preprocessor to
for( int i = 0; i < 10; i++ ) printf( "Hello %d\n" , i );
Which is very powerful, but obviously open for abuse. I very rarely if ever use macros for constants, instead I will define the values as const in a .c file and then declare it extern in the header like
const int kAnswerToEveryThing = 42; // .c file
extern const int kAnswerToEveryThing; // .h file
I have one project that I use macros quite a bit, this is in Objective-C not c, but the macro system is identical and I have defined macros that expand out into class methods which add meta data to a class to be used by my library, its to do the same functionality as Java's annotations.