tags:

views:

1880

answers:

14

Why does C++ need and use pointers? I know they add power to the language but they make it a lot harder to understand for beginners. Languages like F#, Java, Ruby, Python, Lua, etc. get by just fine without them, and they're quite powerful.

+10  A: 

C# has pointers, and I couldn't get by just fine without them. It completely depends on what you are doing, and learning pointers is extremely good for you as a developer. The question isn't why, it is when to use them.

David Anderson
A: 

I think iterating through a (file)stream is a lot easier with pointers. And if the data in the (file)stream is always the same size you can just go through it by saying pointer += sizeof(data); But ya... you're right. It's quite hard to understand in the beginning. Maybe there should be a better documentation for it.

shevron
when voting down... could you please tell me what's wrong with my post?
shevron
I didn't downvote you but, saying C++ has pointers because it is easier to iterate the filesystem is at least.... a .. short attempt of answer. It has todo a lot more with memory management than with filesystems.
OscarRyz
Ok that's an answer I can accept ;)Ja I'm stilll learning all of this stuff... so I don't know all things pointers can do for you; ;)
shevron
A: 

This question can start a serious flame war. I asked myself the same thing over and over while trying to get my head around pointers and all the related stuff in c++

On reason languages like ruby, python and others are on another level of coding. They are more abstract farther away from the machine language. But maybe slower.

Another reason is that c++ is a very old language. Many concepts are from times people didn't know any better and I think that is a serious problem. C++ has its advantages it lets you write very fast code and take great shortcuts. But the tradeoff is a language that is hard to understand and programs that look like art but puzzle the persons working with it later.

Janusz
I would disagree with your assertion that "people didn't know any better" -- pointers are very powerful and useful if one needs them. Something along 'using the right tool for the job'. Many beginners do not learn via any structured method (i.e., instructor-led classes), therefore they lurch along, picking up poor habits (SQL injection vulnerabilities, misused "goto" statements, mixing business logic in the view, etc) and not "getting" things like pointers---which is a shame, really.
BryanH
Yeah I really, really disagree with that last statement. Every operating system you use today was written in C/C++. Not a single one was written (or even could be written) in Java, Ruby, or whatever the hip new language is. To say people who write operating systems "don't know any better" is an insanely ignorant statement.
Bob Somers
@Bob Somers: Since you're right about the current OSes I wouldn't bet that there may be OSes in the future that will be written in Java or similar. This would be the case as soon as there is hardware (CPU) that directly implements the VM of those languages!
rstevens
@rstevens: You can't really implement the VM in hardware. The only way you could do it is by implementing a substantial about of the VM in firmware... which would just be C code anyway... which is what we've already got. :P
Bob Somers
As soon as you have a physical machine, the VM in VM cannot stand for Virtual.
Tom Leys
@Tom Leys, yeah, but the JVM byte code machine could be implemented with hardware assist. :-)
Nosredna
I don't say that nobody will use pointers anymore. They have their use and they will be needed. But I say that people who are not familiar with pointers or overfamiliar will produce code that is hard to read. And in a time where maintainability often comes over speed this kind of pointer vodoo often is counter productive
Janusz
+21  A: 

Maybe C++ isn't for beginners.

Pointers have been around for a long time. They were in Pascal and C. When C++ came out, it would have lost out of the gate without pointers.

Nosredna
+1, and a loud AMEN! -- why must EVERYthing be suitable for beginners?!
Alex Martelli
um, so they can figure out how to use it?
RCIX
What's so hard to understand about pointers? Even nowadays, programmers learn that instructions and data are stored in memory at addressable locations, right? The pointer just says what the location is. What's so hard? I learned assembly language before C, though. Maybe assembly language programmers have an advantage when learning C pointers.
Nosredna
@RCIX. We shouldn't have space shuttles. They are so hard for beginners to fly.
Nosredna
I don't think you can go out and download instructions for a cut-out space shuttle. My point is that if anyone can go out and start programming in it, then there should be a reasonably easy introduction to it. Plus, i've heard many horror stories about how doing nearly anything in c++ can blow up when you least expect it. However Alex Martelli has a good point and i understand now why c++ offers pointers, and i'll accept that you should probably learn in other languages before moving onto an "expert" language like c++.
RCIX
It's not the language's job to write its own introductions. Someone certainly could write an introduction to C++ that doesn't use pointers. You don't have to use everything the language has. Garbage collection would have been a disaster on the machines I was programming when C++ came out. I worked on games--you couldn't have a GC just decide to freeze things for a few frames. Even when Java came out, is was slow for years. Have you done any assembly language?
Nosredna
Honestly, C++ is not that hard. If you're writing code where "doing nearly anything will blow up when you least expect it" that is more a reflection of your poor coding ability than the language. A poor craftsman blames his tools.
Bob Somers
Sorry, but I honestly distrust the ability of any programmer who is unable to understand pointers after a bit of study. It's really not that difficult a concept.
Ed Swangren
A quibble: Pascal supports references into the heap which may be `nil` which it calls "pointers", but all the other languages discussed (F#, Java, Ruby, Python, and Lua) have that too. Pascal doesn't support pointer arithmetic, casting integers to pointers, pointers into the stack and into structures and in global variables, and the other things that make C++ pointers particularly error-prone.
Kragen Javier Sitaker
Funny thing is that a lot of difficulties I experience when learning C++ wasn't the language per se, but other things like learning how to link with external libraries, or even stupid things like accidentally using the same include guard in different files (due to copy-paste lazyness) could keep me puzzled for ages..
StackedCrooked
I know this is a year late but I can't resist:@RCIX: You can't download instructions for a cut-out space shuttle, but you CAN download instructions for a real one: http://www.nasa.gov/centers/johnson/pdf/390651main_shuttle_crew_operations_manual.pdf
Maulrus
+40  A: 

All other languages you mention (and you forgot, at least, Java!!!), while each very useful and usable, don't let you get anywhere as close to the machine as C++ (and C) allow: simply put, all of those languages impose on you a higher level of abstraction... which may mostly be fine but will occasionally get in your way.

C++ is a bigger and more complicated language because it allows programming at really low levels of abstraction (very close to the machine) AND at pretty high levels (close to many of the languages you mention) within the same language, indeed within the same source files.

Beginners are well advised to stay FAR away from this amount of power and (inevitably) complication -- but not every programmer is a beginner, and not every bit of code needs (or, actually, can at all stand!-) being within an environment that has "let's protect the poor shmucks from themselves" as a major design goal!-)

Alex Martelli
"Beginners are well advised to stay FAR away from this amoutn of power and ... complication..."Except that beginners are also often pointed to languages which provide nearly equally difficult concepts, if not the same features provided by pointers anyways.
Jimmy
IMHO, now that Pascal is SO out of fashion, beginners could most usefully start with Python or Ruby (if you're in the "give them early easy success" camp in education), D or C# or Java (for a bit more rigor), or Haskell or maybe SML (if they're math majors;-) [or maybe some of the other functional languages]. I have a long-time love story with Scheme, but I understand why MIT dropped it for beginners in favor of Python...
Alex Martelli
Usually when I see Alex answer a question, I read it to learn a better answer than I could provide. While I'm no C++ expert, Alex's comments are well founded in what they're saying, they don't - in my opinion - provide the correct answer to the question. The answer is simple, and what bluebrother already said: From the start, Stroustrup has made it a high priority to have C++ be a superset of C, thus since C has pointers, C++ must have them. Last fall, Stroustrup gave this talk: http://www.dcacm.org/archives/Lists/2008%20Events/Attachments/6/stroustrup_dc_acm_50th.pdf
PTBNL
I assume there are many different ways to learn something. I always remembered pointers to be a very direct, and thus very easy understandable concept, much less opaque than any classes, objects, references and instances. And while, yes, basic tools let you fumble in very basic ways, they also teach you very basic (and useful) concepts that help to understand the more complex things. Thus I'd rather say "start with pointers", for it makes it easier to understand the concepts (and use of references) later. Given you have sufficient time for learning, of course.
Don Johe
I learnt pointers with Pascal at university and then I used in next course for a C lab. Then at work (I thank every time my ex boss!) I learnt C++. The year after in university they changed the learning language from Pascal to Java... and I was very happy to be born one year before :)
Patrizio Rullo
+1  A: 

Pointers provide a means to pass by reference, which is crucial in some programs that pass large data structures. Instead of passing 100mb, you just pass a small pointer. Languages without "pointers" usually have a mechanism to pass by reference.

Scott
Alex Martelli
For that matter, try writing a swap function in C# or Java without explicitly declaring parameters as a reference. It's suddenly a bit difficult. They use something quite similar to pass-by-reference, but a better name is eluding me at this point.
Jimmy
I understand that behind the scenes, c# and java and all of that use pointers but my original question is why c++ has you dodeal with pointers "in front of the scenes". I understand that now.
RCIX
+1  A: 

Most higher level languages don't have pointers per se, but they do use similar constructs. Here's an example. In C++, if you have something like:

Foo myObject();

you've declared an instance of a Foo, which is always going to be of type Foo. You can't declare a Foo and instantiate another type without using a pointer. However, in C#, you can do it easily:

Foo myObject = new Bar(); // assuming Bar derives from class Foo

The only way to do this in C++ is with a pointer (and thanks to polymorphism). C# is using a pointer of sorts, but abstracting out the messy stuff that makes pointers so "hard" to use.

Jimmy
C#, like Java, does a good job with references (better than C++), but ALSO provides pointers (differently from Java!) because some jobs (e.g. requiring address arithmetic) are just better done that way!
Alex Martelli
Since pointers are just integers of a specific size you could also use "pointers" and do pointer arithmetic in Java! The point that there is a specific type in .NET normally used for pointers (IntPtr) does not prevent you to also use "int pointers".So if you look it from this side: All languages could have pointers if you want. The question is just if it is possible to get the address of a memory block (object, etc.) directly. (I think you could also do this in Java with help of native code called from Java)
rstevens
@Jimmy - polymorphism works via C++ references too.
Daniel Earwicker
+5  A: 

You're mixing up pointer arithmetic with immutable pointers, AKA, references. All of these languages, including Java, which you didn't mention, do have references. References are slightly less powerful than pointers, but you won't notice this until you get to the stage where you need pointer arithmetic or double or triple pointers. But, under the hood, references are really the same thing as pointers, just that the language won't let you do whatever you want to them (i.e., they're not first-class objects).

Consider this python code:

class X: z=13

y=X()
def f(aa): aa.z = aa.z+1

print(y.z)
f(y)
print(y.z)

f() changes the value of y.z, and this is exactly what would happen in the corresponding C or C++ code written with pointers.

zvrba
+1 Finally, the answer I would have posted - "you are using pointers, but you don't know it"
Tom Leys
+3  A: 

In short, because C++ targets systems programming.

What this means is that C++ is oriented around implementing pretty much everything, from top to bottom.

This includes Operating Systems, where you need to have a level of control of what's happening down to the machine address, not just the VM mapped logical addresses.

This also includes compilers for C++ or any other language, which requires actually implementing the abstractions used by those languages.

This also includes performance constrained settings such as embedded devices programming, or high performance computing, where it's necessary to program in a way that makes very careful use of memory, of instructions, of code size, and any other constrained resource.

Not very many languages target this broad range of tasks. Calling other languages powerful by this standard is rather misleading, because those languages are simply not suited to those tasks.

TokenMacGuy
I remember when Java came out, a lot of the discussion was, "well, no pointers--this will be of limited use."
Nosredna
+4  A: 

Why does C++ need and use pointers?

C++ doesn't need anything. Programmers need them and there are programmers who really need them. Like programmers who are building device drivers.

So, there must be some languages that allow raw memory access. C++ happens to be one of those languages.

Nick D
If it didn't have pointers, would we even need C++ anymore? We could use C and assembly for the lowest level and Java or C# on top.
Nosredna
C++ is a multi paradigm language. I don't know if it would have had the same success without pointers, but ... maybe.
Nick D
+11  A: 

One reason I've haven't read yet here:

C++ was designed with compatibility to C as a goal, so simply put C++ is a superset to C (which is not 100% true, but almost). As C does have pointers (and, due to its low level nature needs them) C++ also needs to support them.

bluebrother
True, and C++ needed to do everything C could do to become a language systems programmers would be willing to use.
Nosredna
+1  A: 

You can do a lot in C++ without using pointers. Stick with references and higher level things like the STL. Read Accelerated C++ for a good beginner (albeit someone who has programmed in another language) book. C++ can be programmed in a much higher way than C. Stay away from stuff like multiple inheritance, writing your own templates, and pointers at the beginning and you'll be fine. Do learn about virtual functions and object oriented programming from the get go if you are just beginning. Stay away from overloading. Get the first 50% of the language and the hard to learn extra 50% will seem a lot less disconcerting.

+9  A: 

Lots of good answers here, but there aren't very many good examples of why it's needed. ... Or why C is sometimes called "Portable Assembly Language."

On the lowest level of abstraction on the machine, there are a large number of hardware functions that are accessed through memory ranges. These memory addresses are often quite standardized with various types of hardware.

For example, when an x86 computer first starts up and BIOS has loaded and started the boot sector, the CPU is in a mode called "16-bit Real Mode" for memory addressing. To access hardware peripherals, there are a few methods, including memory regions and the IN and OUT assembly instructions. Video is accessible at the memory address range 0xA0000-0xBFFFF. Writing to this memory location will draw characters to the screen. Writing to certain regions above 0xC0000 manipulates video BIOS registers, which can, for example, change video modes.

C was initially created to port UNIX to the PDP-11, which uses a memory-mapped I/O scheme similar to the x86 today. UNIX would have never run on the PDP-11 without pointers.

Languages like F#, C#, Ruby, Python, Lua, etc. can't do that without modifying the core language. C and C++ can:

/* Assuming 16-bit DOS environment, 80x25 character video mode. */
char* video = 0xA0000;
video[1] = 'H';
video[3] = 'e';
video[5] = 'l';
video[7] = 'l';
video[9] = 'o'; /* prints "Hello" in the top-left corner of the screen.
greyfade
Not all systems have memory mapped IO. Some CPUs have "ports."
Nosredna
@Nosredna: Which results in even less beginner friendly techniques, like the Duffs Device
TokenMacGuy
@Nosredna: I mentioned that with the IN/OUT x86 instructions. I realize not all systems use MMIO, but it's fairly common and the PDP-11, for which C was originally designed, uses MMIO.
greyfade
+1  A: 

Garbage collection (GC) is assumed to be too much overhead for some of the environments where C++ will be used, e.g. embedded systems, operating systems. With high-level references, there is no way for an object to be deleted if it is still accessible. That safety guarantee is made possible by the assumption that GC is there. Without adopting GC as a basic assumption, C++ will always need raw pointers.

Unsurprisingly, one of the most popular C++ questions on this site is "How can I solve the dangling-pointer problem in a general way?", and the most popular answer is to use a reference-counting smart pointer, which is like a poor man's GC. Another answer is to use the right tool for the job - if you aren't doing low-level or embedded systems programming, C++ is probably the wrong tool. C++ is used far more widely in high-level application programming than it probably should be. A lot of people are wasting time debugging memory leaks, memory corruption, etc. just because they're using the wrong tool for the job.

Another reason for using pointers is that they allow the author of a device driver to address a specific region of memory, which is often useful when communicating with devices because certain areas of memory are "mapped" to the hardware device. But again, this is very much a low-level systems programming concern.

Daniel Earwicker