Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to explain declarative fallacy in C++?

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?

like image 711
ybakos Avatar asked Sep 01 '09 06:09

ybakos


People also ask

What is declarative programming with example?

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.

How does declarative programming work?

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.

Is declarative programming better?

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.

What is declarative syntax?

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.


1 Answers

Tell the author that

pounds = newtons/NEWTONS_PER_POUND;

commands the CPU to

  • take the value at the address referred to as "newtons"
  • take the value at the address referred to as "NEWTONS_PER_POUND"
  • divide them
  • store the result at the address referred to as "pounds"

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;
like image 96
Zed Avatar answered Oct 13 '22 10:10

Zed