Re: const problem
pereges wrote:
Yes. Most things in life are just choices.
The point of const (in C) is to help the compiler to do more checks on
your source. Consider this trivial program:
#include <stdio.h>
int main(void) {
long double pi = 3.1415926535897 932384626433832 795029L;
long double r;
puts("Enter radius of circle:");
scanf("%Lf", &r);
printf("Area of the circle is: %Lf\n", pi * (r * r));
return 0;
}
Now imagine this as a part of a much larger program or function.
Obviously 'pi' holds the value of a constant and should not be changed.
However if some other code in your program happens to modify 'pi' your
compiler will silently accept the modification and your program will
start giving you wrong or inaccurate results. This is where
qualifying 'pi' with const will start paying off. Now anywhere a direct
change is made to 'pi' the compiler will give you a diagnostic warning
you of it, so you can correct the code and prevent undefined behaviour.
As someone else said, const may appear rather meritless for small,
one-man programs, but it will start paying dividends when the program
grows larger and is developed by a team, even in spite the quirkiness
of C's const.
PS. You can still attempt to write to a const object and evade compiler
warnings by writing through a pointer, but that's far less likely to
happen in real code than direct in-advertant modification.
pereges wrote:
I have always found that using const is only a choice rather than a
necessity.
necessity.
But this is just my opinion, I'm sure the experts here will
differ.
differ.
your source. Consider this trivial program:
#include <stdio.h>
int main(void) {
long double pi = 3.1415926535897 932384626433832 795029L;
long double r;
puts("Enter radius of circle:");
scanf("%Lf", &r);
printf("Area of the circle is: %Lf\n", pi * (r * r));
return 0;
}
Now imagine this as a part of a much larger program or function.
Obviously 'pi' holds the value of a constant and should not be changed.
However if some other code in your program happens to modify 'pi' your
compiler will silently accept the modification and your program will
start giving you wrong or inaccurate results. This is where
qualifying 'pi' with const will start paying off. Now anywhere a direct
change is made to 'pi' the compiler will give you a diagnostic warning
you of it, so you can correct the code and prevent undefined behaviour.
As someone else said, const may appear rather meritless for small,
one-man programs, but it will start paying dividends when the program
grows larger and is developed by a team, even in spite the quirkiness
of C's const.
PS. You can still attempt to write to a const object and evade compiler
warnings by writing through a pointer, but that's far less likely to
happen in real code than direct in-advertant modification.
Comment