How might one craft a good explanation of why the following code is not correct, in that the author is attempting to write C++ code declaratively rather than procedurally?
const double NEWTONS_PER_POUND = 4.448;
int main()
{
double pounds, newtons;
pounds = newtons/NEWTONS_PER_POUND; /* pounds equals 'unassigned variable'/4.448 */
newtons = 10.0;
cout << pounds << endl; /* a big number, not 10.0/4.448 */
return 0;
}
The author expected cout
to display a proper calculation, but instead gets a "crazy number."
I would explain this as "C++ is procedural, and therefore at the time of the declaration
pounds = newtons/NEWTONS_PER_POUND;
newtons
has not been assigned a value.
Any better suggestions? Or an explanation why C++ isn't "smart" enough to carry out the behavior the user mistakenly expected?
Declarative programming focuses on the end result, while imperative programming focuses on how to get there. For example, when you jump in a taxi, you declare to the driver where you want to go. You don't tell him how to get there by providing turn-by-turn directions.
Declarative programming is a programming paradigm in which the programmer defines what needs to be accomplished by the program without defining how it needs to be implemented. In other words, the approach focuses on what needs to be achieved instead of instructing how to achieve it.
Though imperative programming is easier to reason about for beginners, declarative programming allows us to write more readable code that reflects what exactly we want to see. Combined with good variable names, it can be a powerful tool.
The declarative syntax is a programming paradigm that allows you to write code in a more formal and procedural way. In essence, the declarative syntax is a way of describing the code you want to write, without having to worry about how it's going to be implemented.
Tell the author that
pounds = newtons/NEWTONS_PER_POUND;
commands the CPU to
what he is looking for is most probably a function in imperative terms:
double newtons_to_pounds(double newtons) {
return newtons/NEWTONS_PER_POUND;
}
...
newtons = 10.0;
cout << newtons_to_pounds(newtons) << endl; /* a big number, not 10.0/4.448 */
return 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With