0

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?

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • 3
    Any scenario where an integral constant expression is required – StoryTeller - Unslander Monica Jul 17 '17 at 10:24
  • One defines a preprocessor macro, and the other defines a variable. Preprocessor macros are used to *replace* parts of the code, and are compile-time only constructs. Variables exists as entities in the program, and can change value at run-time. If you need a pointer to a variable, then a macro can't be used. Variables can't be used when compile-time constants are expected. – Some programmer dude Jul 17 '17 at 10:24
  • In the first case LIMIT is a constant. And it will be "replaced" with the value 100 before compile. You can also write "const int LIMIT = 100;" to declare a constant – Anoroah Jul 17 '17 at 10:25
  • If you feel that one of the answers answered your question, please accept it to make this question more helpful for future users. – Akira Aug 02 '17 at 07:31

2 Answers2

1

#define LIMIT 100 define LIMIT as an integer constant while int LIMIT= 100; declare it as an integer variable.

haccks
  • 104,019
  • 25
  • 176
  • 264
1

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.

Akira
  • 4,385
  • 3
  • 24
  • 46