lvalues, rvalues, and eigenvalues, oh my!

OK, maybe not eigenvalues.

But understanding rvalues & lvalues are important to any understanding of C programming.  Even if this isn’t a C programming blog (I’ve no allusions about my ability to program independent of useful examples), these components are important to understanding how a MUD works.

Traditionally, lvalues and rvalues were defined based on their proximity to the equal sign in an equation, for example in the statement:

x = 7;

x is an lvalue and 7 is an rvalue.  The statement:

7 = x;

wouldn’t make any sense to a C compiler (even if it makes sense algebraically) because 7 can’t be an lvalue (it is not an address).

A variable like X has two values, at least as far as the compiler is concerned.  One value is it’s memory address, the other is the value stored in that memory address.  Normally, we refer to the variable itself (i.e. X), which tells the compiler to look at the memory location (lvalue) associated with that variable and extract the value (rvalue) stored there.

Another way to get at the value stored in memory is to use a pointer.  A pointer is a variable that stores the address of another variable.  This is useful for referencing large data structures and modifying data in other functions.

For example, take the CHAR structure (see structs.h).  Each character or NPC in the mud has its own set of data that describes how the (N)PC interacts with the mud.  As we use various functions to refer to these CHAR structures, it doesn’t make sense to constantly copy the struct to a new place in memory.  It would be better to be able to refer to the one memory location storing each char struct so that our memory doesn’t get overloaded almost immediately.  Not only that, but pointers allow us to modify the character structure in sub-functions.

If you look through the tbamud code, you’ll see a lot of functions that appear as follows (for example):

void hit(struct char *ch, struct char *vict)

This function takes as its input a pair of char structures (the attacker and the victim), but doesn’t copy the entire structure.  Rather, within the hit function, ch points to the address associated with the attacker and vict points to the value associated with the victim.

Anyway, the ability to use pointers to refer to variables throughout the code is an excellent feature of the C programming language, and understanding how they work is important.  There are a number of tutorials around the web on how to use pointers, but  understanding how they work is a lot more difficult than understanding what commands you use to implement them.

Leave a comment