How is correct when declaring a variable that is a pointer?

4

I see that some people do

int* variavel;

And there are those who do

int *variavel;

Which one is correct?

    
asked by anonymous 24.01.2017 / 11:41

1 answer

8

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

int* variavel;

Whoever chooses this option wants to make it clear that the type is a int* , or pointer to integer. Leave the variable name alone. I would normally indicate this more, but it has a problem in a particular statement situation.

int *variavel;

It looks the same but it looks like the type is int and the variable is a pointer. It's pretty confusing. But for consistency this form is ideal unless you never declare more than one variable in the same statement .

What are you stating here?

int* var1, var2;

If you say you are declaring two pointer to integer variables, you have made a mistake. You are declaring var1 as "pointer to integer," but var2 is just an integer. It's weird? IS. But language is like that. The correct would be:

int* var1, *var2;

Now is not the pointer close to the scalar type odd? Coherently it would:

int *var1, *var2;

Although both work.

Some people preach that the good thing is to always leave the pointer close to the type and never use more than one statement in the statement , like this:

int* var1;
int* var2;

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

^int var1, var2;

This would read pointer to integer and everything in that statement is of this type, if you want to declare a int , it should be in another statement . It's more intuitive, but language was not that way.

    
24.01.2017 / 11:41