In below code, foo points to the address where the value of bar is stored. Should I be able to find the address of foo itself using yet another pointer xyz?
Thanks all. I was dreading this, because now this means that using a pointer means using up more stack, not less! That's because we need some stack space to store the address of the variable being pointed to.
However, countering my own observation, I guess the benefit of creating and using the pointer outweighs this increased stack usage. As an example, when passing pointer to a value instead of the value itself as the argument to a function -- in that scenario, the value could occupy several bytes, and presumably the pointer would occupy only as many bytes (or less) as needed to store the hexadecimal address of that value?
If incrementing the stack by 8 bytes or whatever is enough to cause a stack overflow, then you're were already too dangerously close to an issue anyway, and any function call could have also potentially caused a stack overflow. I don't think your specific concern about declaring a pointer and stack usage is a real concern you have to worry about; usually stack overflows happen because you're trying to allocate large arrays on the stack, or because of an oversight in logic causing infinite recursion.
Yes, the benefit of passing by pointer is that it avoids a copy of the object, which may be expensive to copy. But note that in C++, often you don't need to use pointers (at least, not as much as in C). For small types like int, it is recommended to just pass by value. For large objects, pass by const reference to avoid the copy. And if you need to change the object being passed, pass by non-const reference.
Thanks all. I was dreading this, because now this means that using a pointer means using up more stack, not less! That's because we need some stack space to store the address of the variable being pointed to.
you don't need to worry about the stack unless you are on a small embedded system or exceeding foolish in how you manage it. It is very, very large in terms of what should be on it. Remember that most C++ is passing around objects that mostly have large data on the heap anyway: your vectors and stl containers are just a few bytes on the stack with the data hidden in a pointer, and your own classes should follow the same design and have bulk data internally in these containers not on the stack.
pointers are a fixed size, usually the machine's (or operating systems' !!) word size. That is a 64 bit computer will use 64 bit pointers but if you put dos on it, you get 16 bit pointers and if the hardware is backwards compatible it works. Assuming the os matches the hardware, its the machine word size, even if it would 'fit' in 8 bits. Its just more efficient to have fixed sized things in general, at that level.