I
I
Incerti2019-04-06 16:45:14
C++ / C#
Incerti, 2019-04-06 16:45:14

What is the difference between pointer assignments?

how is
int *ptr=&a;
from
int *ptr;
ptr = &a;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DevMan, 2019-04-06
@Incerti

nothing.
in the first option - the declaration and assignment of value.
in the second - splitting into two operations.
any sensible compiler will lead both codes to the same thing. that is, the difference is only in readability.
https://godbolt.org will help you, it will show what the resulting code will be.

G
gradmir, 2019-04-09
@gradmir

There is an ideological difference. In the second case, it is possible to add additional code between the declaration and the value assignment. If it tries to operate on an uninitialized variable, it will result in undefined behavior.
The first option does not allow such liberties, so it is recommended to use it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question