Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Both languages have the same syntax.

Why does C have the weird * character that denotes pointers (which is some kind of memory address of the variable contents?), when PHP doesn't have it and you can do pretty much the same things in PHP that you can do in C, without pointers? I guess the PHP compiler handles this internally, why doesn't C do the same?

Doesn't this add unneeded complexity in C? For example I don't understand them :)

share|improve this question
41  
"you can do pretty much the same things in PHP that you can do in C" Can't tell if trolling or serious. –  Mahmoud Hossam Apr 11 '12 at 22:37
5  
Couldn't one make a similar gripe about the $ character used in PHP to denote a variable? –  JB King Apr 11 '12 at 22:57
5  
@MahmoudHossam: If PHP is involved, then it's trolling. –  Thomas Eding Apr 11 '12 at 23:18
12  
@AnnaBanana he's not suggesting, he's stating a fact. :P –  Mahmoud Hossam Apr 11 '12 at 23:21
12  
"but they can be easily replaced by using the global keyword" Can't tell if trolling or serious. –  TokenMacGuy Apr 12 '12 at 0:18

9 Answers 9

up vote 23 down vote accepted

Like so many things, the answer is of the form "Because X and Y are different things with different purposes".

In this case, the designers of both languages assumed that the users of their languages had a very different set of goals. For C, the primary use case was "portable assembly language", which really means getting down into the nitty-gritty of how the computer is actually managing its resources. There's no practical way to avoid memory address manipulation at the lowest level of abstraction, and so C has robust support for it.

PHP was intended to make dynamic web page content as flexible and painless as possible. This is quite a few steps removed from the super-low level of the C world; managing memory is, for the purposes PHP is intended to address, much too low level to be of much interest. Any kind of automatic memory management would be fine, so long as it is robust and reliable, and stays out of the way. That's exactly the situation you see in PHP; objects are allocated automatically, when needed, and garbage collected when they are no longer useable, and it all happens without the intervention of the PHP programmer.

It's perhaps of some interest to observe that PHP is itself written in C! the nitty gritty of memory management is written in C, which provides the tools needed to do that kind of thing, so that the language created, doesn't require the programmer to do much themselves.

share|improve this answer
4  
According to Lerdorf PHP was designed for non-programmers. And that is obviously the root of all evil. It is a contradictory design goal which leads to oversimplification and in turn to more complexity. Face it: using a programming language makes you a programmer. Imagine a car designed for non-drivers. Imagine surgeon tools designed for non-surgeons. –  ThomasX Apr 12 '12 at 9:44
1  
@ThomasX, while I don't want to leap robustly to the defence of PHP or anything, isn't a fairer analogy "a car designed for non-mechanics"? That car is still occasionally going to break down and cost you a packet, of course... –  thesunneversets Apr 12 '12 at 16:20
    
I do agree that some of the simplicity can lead to a ratking of code, but just because it's easy to write bad code doesn't mean it's hard to write good code. RoR is adamant about duck-typing, and everyone sucks their ruby balls. PHP does type juggling and everyone snickers and acts like it's coding for retards and housewives. Jquery could be called "javascript for people who don't want to deal with javascript's bullshit" but that doesn't make it a contradictory design, it makes it the best thing to happen to browser-side code. It makes it smarter. –  Anthony Apr 19 '12 at 8:07

You can accomplish much of the functionality of pointers by using integer operations on an array index. This integer index is often called a cursor.

Instead of manipulating a pointer value char *p, you manipulate the cursor int i and index the array arr[i] to yield the value in that memory cell.

To some extent, this is just putting fancy names on obvious facts. But having names lends credibility to a valid technique that may be easily overlooked. :)

The real advantage is that familiarity with this allows you to translate code using pointers into languages that don't have them.

share|improve this answer

Yes to all of the above. But there are other things to consider.

(type *T) list ~ (type T) list[]  // pointer can be used as an alias for an array

The only difference is that an array is a constant pointer, meaning it cannot be reassigned to point to something else. And,

*(list + n) = list[n].

To sort a list, especially a multidimensional one, it is more efficient to just move the pointers around. There is no need to copy and drag data around.

What (* = deference) means depends on context. Pointers are always declared using it, e.g. char *p, int *n, struct record *rec.

In a statement (*) returns the value pointed to. Thus.

char ch = *p;   // ch = value p is currently pointing at.

In C++ you can use pointers to get base class data or methods from a derived class, provided that the classes are properly defined.

Certainly, the understanding of pointers takes time, but necessity often facilitates imaginative uses.

Contrast this with PHP which is an primarily designed to be a back end language. Although it can be sophisticated in implementation, it was not designed for robust computing.

share|improve this answer

You actually can't do the same things in PHP, if it concerns actual (physical, not pretend virtual) hardware and/or video bitmaps (etc.) at fixed non-remapped physical addresses, perhaps in some constrained number of CPU cycles.

Web sites are not the only things run by software.

share|improve this answer
4  
+1 for "Web sites are not the only things run by software". A lot of people seem to think that software development is always web development... –  EricSchaefer Apr 12 '12 at 16:39
1  
And php is not only used for web dev tho. A lot of people seem to think that php is for web only... –  Florian Margaine Sep 23 '12 at 14:55

C is a systems programming language, which can be used to create things like device drivers, embedded software and operating systems.

PHP is a scripting language used to create websites.

They're not the same thing at all. Apples and oranges.

It is not true that both languages have the same syntax. The C language requires that variables be explicitly declared. PHP deduces a variable's type from its usage. Parameter passing is different. Rules about variable scope are different. There are some syntactical similarities, but it's not true that they use the same syntax.

Address oriented operations (which are enabled by the availability of pointers) are required by many low level tasks that the C language is used for.

share|improve this answer
    
Creating websites is a very common use for PHP, but it's certainly not the only one. –  Andy Lester Sep 23 '12 at 23:39
1  
Understood - but writing device drivers is not a use for PHP either, hence the lack of pointers. –  Scott Wilson Sep 25 '12 at 0:16

Pointers in C serve three main purposes:

Faking pass-by-reference

C passes all function arguments by value; the formal parameters and the actual parameters are different objects in memory, so changes to the formal parameter are not reflected in the actual parameter. If you want a function to change the value of something in the caller, you must pass the pointer to that object:

void swap(int *a, int *b)
{
  int tmp = *a;
  *a = *b;
  *b = tmp;
}

int main(void)
{
  int x = 3, y = 4;
  swap(&x, &y);
  return 0;
}

The expressions *a and *b in swap correspond to the objects x and y in main, so writing to *a updates x and writing to *b updates y.

Tracking dynamically allocated memory

The C memory allocation functions malloc, calloc, and realloc all return pointers to the first element of the dynamically allocated buffer.

int *arr = malloc(sizeof *arr * N); // allocates a block of memory large
                                    // enough to hold N ints

You can apply the subscript operator to a pointer as though it were an array (the subscript operation a[i] is equivalent to *(a + i); that is, offset i elements from a and dereference the result).

Building self-referential data structures

Although generations of Fortran programmers were building lists, trees, queues, stacks, etc., without them, pointers make building self-referential structures very easy, such as this binary tree node:

struct tnode {
  K key;                // for some arbitrary type K
  T data;               // for some arbitrary type T
  struct tnode *left;   // explicitly points to left subtree
  struct tnode *right;  // explicitly points to right subtree
};

I'm not familiar enough with PHP to say how you would do these things in that language. I would point out that C predates PHP by at least a couple of decades, and that PHP is pretty specific to a particular domain.

As to why C doesn't handle all this automagically...

One of the guiding philosophies of C is to keep the language as simple as possible, making it relatively easy to implement. Automatic memory management would add some complexity to the language (adding the threading library in C11 certainly did). Not to mention that automatic memory management can also play hell with performance-critical code.

share|improve this answer

PHP does allow you to use pointers, as you can see in the official documentation on References.

It's not exactly the same thing as in C, as the latter does allow you to allocate memory very precisely, but pointers are present in a lot of language.

Basically, remember that every time that you create an array or a class in an object-oriented language (C++, C#, Java, ...) you actually create a pointer that is stored in the variable. What allows you to skip the * operators is some kind of synthaxic sugar.

share|improve this answer
    
that page links to.. php.net/manual/en/language.references.arent.php –  AnnaBanana Apr 11 '12 at 22:43
1  
They are not exactly pointers, as I explain later you can do deeper things in C. But one of the main goal of pointer is to be able to pass arguments to function by reference. And that's exactly what is said in the doc. –  SRKX Apr 11 '12 at 22:45

C is a pretty low level language, it's pretty much one step removed from Assembly (and C was designed to be a portable assembly). It's an abstraction of the machine, and uses pointers because it allows you to operate at the machine level, and back then you would use pointers to directly access memory (virtual memory has made this practice mostly arcane).

Note that C was created in the 70s, when computers were far simpler than they were now, and direct memory addressing was how software worked. Pointers are also used for things like arrays (you could say arrays are syntactic sugar for pointers in C), and dynamic memory allocation to create data whose size may be unknown at compile time.

PHP is much newer than C (late 90s) and is heavily influenced by C in its design, but it, like many other languages newer than C, abstracts away raw pointer usage and instead uses things like References, which are like limited pointer, in that they can refer to other data, but you can not do things like perform pointer arithmetic, nor do they represent addresses.

PHP was designed to be easy for people to learn, and a pain point many programmers have when using C (or C++) is pointers, so PHP and many other languages abstract away pointers and use references, objects, implicit heap allocation, etc. to hide pointer usage from you. Internally, PHP will be using pointers (it is written in C, after all), but you yourself do not have to be concerned about that.

As for complicating C? I think C is a rather simple language (the de facto book is 300 pages and shorter than most other language books), but pointers do take some mental work to understand.

share|improve this answer
2  
virtual memory doesn't diminish pointers importance a bit. –  Javier Apr 11 '12 at 23:24

PHP is actually an extremely limited language. It can do one thing well--produce webpages--because it was only ever designed to do that one thing. But if you wanted to build a 3D game, or write an operating system, or create a competitor to Photoshop, you wouldn't want to do that in PHP!

C, on the other hand, is a general-purpose language. It was first designed to build operating systems, which provide an interface between the hardware and the rest of the software. To do that, you need a concept of direct memory access. (For example, if you want to send something to a printer, you need to be able to send data over a network, you need to be able to write directly to the location in memory where the network hardware's input buffer is located.) That's what pointers are really for.

The problem with pointers in C, and the thing that makes them difficult to understand, is that in C they're used as a "magic hammer". Earlier languages had better ways to do certain things that in C are only available by using pointers. (FORTRAN had pass-by-reference, and ALGOL and Pascal had real arrays, for example. C has neither; you have to fake both by abusing pointers.) Since they're used all over the place for many different things that can and should be done other ways, it makes it difficult to understand what they're about.

share|improve this answer
1  
What's not "real" about a C array? True, when passed into a function (or assigned) they turn into pointers, but when declared, I think they qualify as a "real" array... just allocated on the stack. –  JoelFan Apr 11 '12 at 23:02
1  
@JoelFan: not only they're as real as any other, but (re)implementing them with pointers isn't 'fake' nor 'abusing pointers'. It's how these things are done. –  Javier Apr 11 '12 at 23:17
2  
@JoelFan: C does not have real arrays, because real arrays have bounds. Even ignoring the "they turn into pointers when you pass them" issue, let's say you allocate int myArray[6]; on the stack. You can then, in the same function, write to or read from myArray[28] and that's perfectly legal to the C language. (You can also access [myArray]28 with the same result!) This is because C does not have arrays; it has pointers dressed up in ALGOL array syntax to make them look like arrays. If it did, the Morris Worm infection (and thousands of hacks like it since then) would never have happened. –  Mason Wheeler Apr 11 '12 at 23:38
1  
@trinithis: That makes no sense. For all practical purposes, the compiler defines what is and is not a legal program. Rejecting illegal code (generating errors) is one of the most significant parts of its job. –  Mason Wheeler Apr 11 '12 at 23:59
1  
@MasonWheeler: Then you are compiling a language similar to C, but not C. That is, you have a compiler for a C-like language that also compiles C. In fact, for the general case, a C compiler cannot reject all illegal C programs. Solving this would solve the halting problem. –  Thomas Eding Apr 12 '12 at 0:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.