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?

4
  • 3
    Any scenario where an integral constant expression is required Commented Jul 17, 2017 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. Commented Jul 17, 2017 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 Commented Jul 17, 2017 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. Commented Aug 2, 2017 at 7:31

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.