for example is there any difference between
#define LIMIT 100
and
int LIMIT= 100;
If not is there any use scenario in which on can be used but the other can't?
for example is there any difference between
#define LIMIT 100
and
int LIMIT= 100;
If not is there any use scenario in which on can be used but the other can't?
#define LIMIT 100
define LIMIT
as an integer constant while int LIMIT= 100;
declare it as an integer variable.
The first one defines a preprocessor macro which will be replaced to its value everywhere in the code during preprocessing.
#define SIZE 4
int main() {
int matrix_1[SIZE][SIZE] = { 0 };
int* array = malloc(SIZE * sizeof(int));
/* ... */
}
The value of SIZE
cannot be changed at run-time. After preprocessing the code above will be changed to the following:
int main() {
int matrix_1[4][4] = { 0 };
int* array = malloc(4 * sizeof(int));
/* ... */
}
The second one initializes an int
variable which will be allocated on the stack and you can modify it on run-time.
int main() {
int size = 4;
size = 12; /* size in now 12 */
int* array = malloc(size * sizeof(int));
/* ... */
}
The size
cannot be used in contexts where an integer constant is required, e.g. as a size of a bit field, as a value of an enum
constant, as case
label of a switch
statement, etc.