Search code examples
c++declarativeprocedural

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?


Solution

  • 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;