Practicing C C++: Continue

The deeper I dive into this topic, the more fascinating and fundamental knowledge I uncover.

Using the swap function outlined in the previous blog, we understand the core concepts of pointers and addresses. In C, however, you can’t pass constants directly to a function like swap(3, 4). Instead, you must assign the values to variables, such as x = 3 and y = 4, and then call swap(x, y). For anyone coming from Python, this might feel odd or even shocking at first. Python allows you to pass constants like numeric values to functions effortlessly, but C operates differently.

This difference exists because Python abstracts away the lower-level, fundamental workings of a computer. However, mastering these lower-level details is essential! In this AI-driven era, high-level languages may soon become less relevant, as for AI, writing code directly at the C or CUDA level is more intuitive and efficient. To remain relevant and supervise AI effectively, we must develop a solid grasp of this foundational level of programming.

So what does Python do to accept constants as inputs directly?

Python accepts constants as inputs directly because it uses pass-by-object-reference (often referred to as “pass by value of the reference”). This abstraction hides the lower-level details of how memory works. Here’s how Python handles it:

  1. Temporary Objects:
    When you pass constants like 3 or 4 to a function in Python, it automatically creates immutable objects for those constants and passes references to these objects into the function. This eliminates the need for the programmer to manually manage variables.
  2. Memory Management:
    Python has built-in memory management with garbage collection, so the user doesn’t need to worry about assigning values to variables before using them in functions. It manages the lifecycle of objects (like constants) behind the scenes.
  3. High-Level Abstraction:
    Python abstracts away pointers, addresses, and other low-level concepts that are central to languages like C. Instead, it uses a reference model where everything is treated as an object, making it easy to pass constants and other values without explicit memory manipulation.

Note Python treats integer(immutable) versus list (mutable) differently, which is reflected in how their underlying methods work.

For lists, appending modifies the object directly:

PyObject* PyNumber_Add(PyObject *a, PyObject *b) {
    // Creates and returns a new PyObject for the result
}

For integers, adding a value creates a new PyObject:

int PyList_Append(PyObject *list, PyObject *item) {
    // Modifies the existing list object in place
}

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.