In C++, if we want to declare multiple pointers, we would do something like this: int *a, *b, *c; where we would have to put an asterisk * in front of each of them. if i write this code: typedef int* ptr; ptr a,b,c;? Will they all be pointers, or just a?
4 Answers
No, typedef isn't just a matter of text substitution (like a macro would be).
typedef int* ptr;
introduces a new name, "ptr", for the type int*.
If you write
ptr a, b, c;
all of a, b, and c will have the same type, int*.
Note that
const ptr p;
likewise isn't the same as
const int* p;
Since ptr is a pointer type, the const applies to the pointer; the equivalent is
int* const p;
1 Comment
Hmmm, interesting... Lets see. Say I don't know many things about typedefs, what do I do?
Answer: I test it by myself. Below there is a code which answers your question:
#include <stdio.h>
typedef int* pointer_t;
pointer_t a1, b1, c1;
int* a2, b2, c2;
int main() {
a1 = new int; // ok
b1 = new int; // ok
c1 = new int; // ok
a2 = new int; // ok
b2 = new int; // compile-time error
c2 = new int; // compile-time error
delete a1; // ok
delete b1; // ok
delete c1; // ok
delete a2; // ok
delete b2; // compile-time error
delete c2; // compile-time error
return 0;
}
Conclusion: Both a1, b1, and c1 will be pointers, but only a2 will be a pointer.
2 Comments
int *a2, *b2, *c2. As said by others, pointer_t will be of type int*, so a1, b1 and c1 will be int *. Splitting your declarations one in each line you have: pointer_t a1; pointer_t b1; pointer_t c1; int* a2; int b2, int c2;Yes, they will be pointers:
typedef int* pointer_to_int;
int main()
{
int a , b , c;
pointer_to_int ptr_a , ptr_b , ptr_c;
ptr_a = &a;
ptr_b = &b;
ptr_c = &c;
*ptr_a = 1;
*ptr_b = 2;
*ptr_c = 3;
std::cout << a << " " << b << " " << c;
}
The output is:
1 2 3
Thats because typedef defines type aliases. On the other hand, if you could use C++11, I recommend you to use using aliases instead of typedef, because its syntax is much clear:
using ptr_to_int = int*;
and also works with template aliases:
template<typename T>
using vector_t = std::vector<T>;
Comments
They will all be a pointers, the typedef is int*.
std::unique_ptrand then just typedef that?int. There's practically never any reason to dynamically allocateint, so presumably, they don't point to dynamically allocated memory.