N
N
Nikita Kotenko2019-02-28 16:27:56
C++ / C#
Nikita Kotenko, 2019-02-28 16:27:56

What is the difference between declaring int* a and int *a in C?

The syntax is already so confusing, why such differences in the declaration, if the result is the same?

/* main.c */
#include "stdio.h"

int a = 10;
int b = 20;

int *a_ptr = &a;
int* b_ptr = &b;

int main (void)
{
    printf("%d\n", *a_ptr);  //10
    printf("%d\n", *b_ptr);  //20
    return 0;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2019-02-28
@n_angelo

Nothing different. Whitespace characters can be placed anywhere where they do not break a keyword, identifier, or constant. All options below are completely equivalent:

int*a;
int* a;
int *a;
int * a;

But there is some subtlety. Looking at the syntax for declaring multiple variables:
it will be seen that the "asterisk" is more of a variable modifier than a type modifier. To emphasize this fact, it is recommended to always write an asterisk next to a variable. This habit avoids stupid mistakes:
int *a, *b; // нормально
int* a, b;  // Ошибка: b кажется указателем, но на самом деле - число.

And the syntax of C is simple.
5c77e725c3f4a317612433.jpeg

V
Vasily Melnikov, 2019-03-01
@BacCM

In C, as in most languages, spaces in code can be ignored. They are just one of the token separators. Moreover, some lexemes are separated without separators.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question