Search code examples
csemanticsalgol68

Semantic differences in Algol and C in casting


Suppose we have the following instructions in Algol 68 and C, respectively: ref int x := 5; and (int*) x = 5;. What are their semantic difference?, it's the same?, because I think that the second one says something like "x will point to a constant" (it can't be compiled) and the first one says "x will point to a memory cell that points to another memory cell that contains a constant, 5". Is it correct?, if not, can you explain it a bit and give some examples to understand this?


Solution

  • I don't pretend to be an Algol 68 (or Algol 60) expert — I've never compiled a thing in either language.

    However, Wikipedia on Algol 68 mode declarations says:

    However, the declaration real x; is just syntactic sugar for ref real x = loc real;. That is, x is really the constant identifier for a reference to a newly generated local real variable.

    Given that explanation, the question's Algol fragment:

    ref int x := 5;
    

    corresponds (more or less) to the C code:

    int *x = malloc(sizeof(*x));
    *x = 5;
    

    putting aside issues of error checking and release of the allocated memory.

    The question's C fragment:

    (int *)x = 5;
    

    is largely meaningless — the result of a cast is not a modifiable lvalue, and you can only assign to a modifiable lvalue. If rewritten as:

    int x_data;
    int *x = &x_data;
    *(int *)x = 5;
    

    then it becomes valid C, though the cast is wholly superfluous. It could also be written to use memory allocation, of course. In C, any use of x to access an integer value (as opposed to a pointer) requires dereferencing in C (*x or x[0]). By contrast, in Algol 68, there's no need to explicitly dereference the variable x.

    Although the question mentions 'constant' a couple of times, I see nothing that implies constancy in the code. The value 5 is assigned to a variable in a location. The value stored in the location can be changed later by another assignment.

    The question title asks about casting, but I see no evidence of a cast in the Algol code, and it is not clear why a cast is considered necessary in the C code.