How is it correct to declare a variable that is a pointer?

Asked

Viewed 90 times

6

I see some people do

int* variavel;

And some people do

int *variavel;

What is right?

1 answer

10


Used this way both are correct and are accepted. The ideal is to choose a shape and always adopt it the same. Let’s see:

int* variavel;

Whoever chooses this option wants to make it clear that the type is a int*, or say otherwise, an integer pointer. Leaves the variable name isolated. I would normally indicate this one more, but she has problem in a specific statement situation.

int *variavel;

It’s all the same but it looks like the guy is int and the variable is a pointer. It’s confusing. But by coherence this shape is ideal unless you never declare more than one variable in it statement.

What are you declaring here?

int* var1, var2;

If you said you are declaring two variables of the "pointer to integer" type, you were wrong. You are declaring var1 as an "integer pointer", but var2 is only an integer. It’s weird? It is. But the language is like this. The correct one would be:

int* var1, *var2;

Now, doesn’t it get weird the pointer next to the climber type? Coherently it would be:

int *var1, *var2;

Though they both work.

Some people preach that the same good is to keep the pointer always close to the type and never use more than one statement in it statement, thus:

int* var1;
int* var2;

If C had chosen another way to indicate pointer would be easier, it could be something like this:

^int var1, var2;

I put in the Github for future reference.

That would read pointer to whole and everything in that statement is of this type if you wish to declare a int, should be in another statement. It’s more intuitive, but the language wasn’t that way.

  • I’d say it’s a matter of getting used.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.