I'd guess that you're thinking of variables the way we think of them in an algebraic expression, i.e. as something with unknown value that depends on the other constraints in the equation:
x + y = 3
In an equation like that, the values of x
and y
depend on each other. If you know what y
is, you can deduce the value of x
. They're called variables
here because there are many pairs {x, y}
that satisfy the equation.
Variables in programming are fundamentally different. In programming, a variable still represents some value, but the value can change over the course of the program. Think of it as a box that can hold a value -- you can always change what's in the box. Some languages might allow an equation like the algebraic one above, but in most languages you don't get to create open-ended constraints like that (at least not without more work). Instead, you'd say something like:
y = 5; // assign 5 to y
x = 3 - y; // y is 5 from the line above, so x becomes -2
x = x - 1; // it's okay to assign an expression containing a variable
// to that same variable, so x now becomes (-2 - 1), or -3
Constants, on the other hand, are just that -- constant values. They're names for values, and those values can't change. We use them mainly to make code easier to understand:
secondsPerDay = hoursPerDay * minutesPerHour * secondsPerMinute;
is easier to understand than:
secondsPerDay = 24 * 60 * 60;