About Dynamic Link

Hi,

I'm learning C++ via a tutorial both with the book and the video. I transcribed the following programme there.

I have the questions as below:

Q1: I don't understand why the tutor assigned p1 to p2 in the Line 16 of fuction create, before going to "while". I think that is redundant because it just creates a node so far.

I remove "p2=p1"from Line 16, and "p2=NULL" from Line 26 , and the result seems same when I run the programme.

Could you please explain why the tutor needed to assigned p1 to p2 before going to "while"?

Q2: In his book he wrote" book* create", but on the video he typed "book*create".
Are they identically same?

Q3: In the book he set "main" as void, but on the video he set "main" to return an int.

Are they alternative?

Many thanks!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 #include<iostream>
using namespace std;
class book
{
public:
	int num;
	float price;
	book *next;
};
book *head=NULL;
book* create()
{
	book *p1, *p2;
	p1=new book;
	head=p1;
	p2=p1;
	cout<<"Please input book number. It ends with the input of 0"<<endl;
	cin>>p1->num;
	if(p1->num!=0)
		{
			cout<<"Please input book price."<<endl;
			cin>>p1->price;
		}
	else 
		{
			delete p1; p2=NULL; head=NULL; return head;
		}
	while(p1->num!=0)
	{
		p2=p1;
		p1=new book;
		cout<<"Please input book number. It ends with the input of 0"<<endl;;
		cin>>p1->num;
		if(p1->num!=0)
		{
			cout<<"Please input book price."<<endl;
			cin>>p1->price;
		}
		p2->next=p1;
	}

	delete p1;
	p2->next=NULL;
	return head;

}

int main()
{
	create();
	return 0;

}
Last edited on
Hi,

Q1: I think the author is initialising the pointer - it's a golden rule to always initialise everything. Not doing so is a trap for young and old.

But I think you should find a better tutorial, the use of new , delete and NULL and raw pointers are frowned upon in modern C++. Instead use an STL container such as std::vector or std::list maybe (if it's worth it).

The trouble with a lot of tutorials is that they are a mixture of C and C++, which also frowned upon.

Q2: there are 3 forms of declaration for pointers and they are all equivalent. However, these are preferred as the pointer is associated to the type ; C++ is all about types:

1
2
book* head=nullptr; // C++11
book* create() {


This might be seen as a personal preference, but I agree with these guys:
https://isocpp.org/wiki/faq/style-and-techniques

Notice the part about 1 declaration per line.

Q3: It's mandated in the C++ standard that main() returns an int.

Good Luck !!
Thank you very much for your help!

I've understood. Have a great day!
Topic archived. No new replies allowed.