Sunny
Sunny

Reputation: 7604

C: how to check if a particular variable has been passed as argument

I have the following code:

typedef struct{
int A; 
char* B;
}MYTYPE;

MYTYPE sample;
int nCount; 

void doSomething(int A, MYTYPE* B)
{
//doing something inside this function.
}

doSomething(nCount, &sample);

Is there a way in my function doSomething() to check if the second argument passsed was exactly sample?

Upvotes: 0

Views: 71

Answers (2)

unwind
unwind

Reputation: 399833

Yes:

if(B == &sample)
{
  printf("Get your own, don't use sample!\n");
}

note that your call is wrong, you need:

doSomething(nCount, &sample);
                    ^
                    |
               IMPORTANT!

Since the function expects an address. It will not build, as written in the question.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

Yes, you can simply compare the addresses.

Remember that a pointer to something is actually the address of that something. So you could do like this:

void doSomething(int A, MYTYPE* B)
{
    if (B == &sample)
    {
        printf("B is sample\n";
    }
}

Upvotes: 3

Related Questions