Can somebody please help me better understand what constant variables can be used for? I am currently on pset3 and i noticed that a constant variable called MAX is used in find.c and gets 65536...but why?? i dont understand what relevance that has to the code, or how it is utilized throughout. Also, there is a variable called INT_MAX and that variable is somehow used to tell a program when to stop asking for input, i dont understand how or why.Please help...and this is my first time using this "forum" so i am sorry if my question or wording isnt right. thanks!
Constant variables, with
const int MAX as an example, the
const means that
MAX will not be modified. It is constant so it must not, and will not be changed. Some reasons for using a
const is; the compiler is forced to throw an exception if you attempt at modifying it, thus catching a bug before you even realize it's there; it also allows the compiler to optimize your code a little better.
That was constants, so now why is it being used in the code, and for what purpose?
65536 is the maximum value an "unsigned short int" can represent, but integers can support up to
2147483647 different values so my assumption is that that using
65536 was just a design decision. Anyways, since
MAX is a maximum it shouldn't change, therefor the variable is promptly declared as a
INT_MAX is a constant defined in
<limits.h> (I think), that simply contains the maximum value of a signed integer
2147483647. So if
straw > INT_MAX bad things will happen because integers aren't that big.
DinosaurCoderSaurus explained to me yesterday that
eof is not a special value such as '\n' or '\0' and others, rather it is just '-1'. You did not mention anything specific nor do I see any mention of it in find.c so I'll leave it at that.
Good question by the way!
Sources and further reading
- https://msdn.microsoft.com/en-us/library/296az74e.aspx // min and max values of data types
- https://en.wikipedia.org/wiki/65536_(number)#In_computing // unsigned short int
- http://www.drpaulcarter.com/cs/common-c-errors.php#4.1 // more on eof