0

According to lectures all variables we use are declared as

int x = something;

or

int x;

But in pset3..in files that Cs50 staff made,they have done;

#define DIM_MIN 3 and #define DIM_MAX 9

So what's the difference between the two and why or why not should i use each of them?

1

You can use these values throughout your entire code, but you cannot change their values. Therefore it's a useful tool for creating global constants in your code.

A bit more info:

#define DIM_MIN 3

Is created by the preprocessor and does not use memory. While the usual int x = something will use memory.

While you can use the value DIM_MIN in your code, you cannot change the value of DIM_MIN, and you cannot pass this address to functions.

So if you need a value that is declared globally like the minimum length or a word, you can use #define while if you need to edit a value, or would like to pass it to a function where it may change, use the int x;

1

when you #define DIM_MIN 3, you are defining a constant not a variable.

what's the difference?

well, there are many differences actually, but probably the most important one is that, in case of a defined constant, you don't have a piece of memory that can be accessed by the name DIM_MIN during runtime (program's execution). so you can't change the value DIM_MIN at runtime. try printing DIM_MIN with gdb!

if the name DIM_MIN is not available at runtime, when is it resolved then?

defined constants are resolved during the preprocessing phase (see the short on Compilers). essentially text substitution happens. that is, when you're defining DIM_MIN to be 3, you're telling the preprocessor: "whenever you encounter DIM_MIN in my code, literally, substitute it with 3". this happens before your program is compiled.

there are many more differences between defined constants and variables, but I'll leave that to you to search for.

when should you use either?

now that you know the main difference mentioned above, it's probably clear now when to use either.

typically, literal values (e.g., 3, which is an int literal) are defined as constants (with #define) to avoid having magical values appearing in your source code for the sake of enhancing readability and making your code easy to understand.

variables are used when you want to store a value that may change (vary) during runtime.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .