Jump to content

(porkchop sneaks into forum )


G+_Michael Heinz
 Share

Recommended Posts

It's basically a response to another comment asking about "why C". C is a very low level language by modern standards. In fact, arrays don't really exist in C, just pointers. (Also, CAVEAT PROGRAMMER - this isn't good coding practice, this is the sort of thing you use to torture recent college grads.)

 

To explain what I mean, you first have to understand pointers. A pointer is a variable that points to a location in memory. For example:

char x = 'C';

char *y = &x;

 

Means that y contains the memory location of x. 

printf("%c",*y)

will print out 'C';

 

Now consider an array, X:

char X[6] = { 'H', 'E', 'L', 'L', 'O', 0};

char *Y = X;

At this point, Y contains the address of the first byte of X, or 'H'.

 

But what if you wanted to print out the values of the other parts of X? Well, you could do it using array syntax like this:

int i=0;

while (X != 0) {

printf("%c",X);

i=i+1;

}

 

OR - you can use pointer math, because C doesn't really have arrays, it only has pointers: When you compile a C program it translates the expression "X" into "*(X+i)", that is, "X is a pointer to some data. Return the value stored in the memory location (X+i)."

 

So, another valid way to do this would be to say:

 

int i=0;

while (*(X+i) != 0) {

printf("%c", *(X+i));

i=i+1;

}

 

And guess what? C strings are actually just pieces of memory that end in a zero. So this:

char X[6] = { 'H', 'E', 'L', 'L', 'O', 0};

 is the same as this: 

char *X = "HELLO";

 And that means you could rewrite the program like this: 

int i=0;

while ("HELLO" != 0) {

printf("%c", "HELLO");

i=i+1;

}

 

But wait! It gets even weirder. From basic math we know that (X+i) is exactly the same as (i+X). So that means you can also do this: 

int i=0;

while (i["HELLO"] != 0) {

printf("%c", i["HELLO"]);

i=i+1;

}

 

And, at this point, you can basically see how the whole thing works - I've explained all of it except the "++" operator (which is shorthand for saying "n=n+1") and the trick where, in C, any expression of the form (x,y) is equivalent to (y).

Link to comment
Share on other sites

Yup. In C, every statement returns a value - even if we ignore that return value 99% of the time. "X=5" itself evaluates to "5" even though we almost never care that it does.

 

It all goes back to C being a language that was designed for machines with only a few kilobytes of RAM - where every byte you saved in your program improved performance and made the machine more capable.

 

These days, no one cares about that kind of thing, but the capability is still in the language specification.

Link to comment
Share on other sites

 Share

×
×
  • Create New...