0

I didn't quite follow the lecture; maybe someone can help me. This is regarding Week 7's "Lecture, continued," about 12 minutes in, when Prof. Malan is going over the simple implementation of a search function.

In the header file, he has defined the struct as containing int n:

typedef struct node
{
    int n;
    struct node* next;
}
node;

Later, in the search function for the main program, he has asked the user for an integer to search for, and declares int n as GetInt().

int n - GetInt();

I am confused as to why these are both called n. As a result, the line of the search function

if (ptr->n ==n)

contains the letter n in two places, but aren't these two n's two different things? (If they're not, then I'm even MORE confused.) Why are they both n? He said this is "a common paradigm," so is it common to call the data in your node n and then also call the thing you are searching for n?

2 Answers 2

1

It's common to use the variable n when we are talking about numbers.

That example also help you to realize that even when those data are receiving the same variable name, they won't collide because they have different scopes (you have to check inside the ptr node to compare if the value n inside it is equal to the value n in main.

1
  • 1
    Ah.. another reason to always be aware of scope, and to remember the difference between my heap memory and my stack memory. Thanks!
    – lacygne
    Jul 22, 2014 at 22:26
1

I am confused as to why these are both called n. As a result, the line of the search function

Why are they both n?

Well, they could have been called anything he wanted. This was just for demonstration purposes (no time to think about names).

aren't these two n's two different things?

Yes, they are different variables. And what he's basically doing here is that he's comparing the value of the variable called n within the structure variable that ptr points to with the variable n that we stored the value we got from the user into.

is it common to call the data in your node n and then also call the thing you are searching for n?

No, it's not. Your variable names should have descriptive names to what they mean or contain.

2
  • Thanks for helping to clarify. I guess I just found it surprising, so I though I might be missing something.
    – lacygne
    Jul 23, 2014 at 21:42
  • @lacygne feel free to upvote the answer and to accept it if it was helpful! Thank you!
    – kzidane
    Jul 23, 2014 at 21:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .