Pointers
This Go code demonstrates the concept of passing values by value and by reference (using pointers) in functions. Let's go through each part of the code with inline comments and additional explanations:
Output
Explanation:
The
zeroval
function takes an integerival
as a parameter by value, meaning it receives a copy of the original value. The function sets the local copy ofival
to 0, but this does not affect the original variable outside the function.The
zeroptr
function takes a pointer to an integeriptr
as a parameter. It dereferences the pointer using*iptr
and sets the value it points to (in this case, the original variablei
) to 0. This modification affects the original variable since it is passed by reference.In the
main
function, an integer variablei
is declared and initialized with the value 1.The initial value of
i
is printed.zeroval(i)
is called, but it doesn't change the value of the originali
becausezeroval
operates on a copy of the value.The value of
i
is printed after callingzeroval
, showing that the original value remains unchanged.zeroptr(&i)
is called, and the value ofi
is modified to 0 through the pointer.The value of
i
is printed after callingzeroptr
, demonstrating that the original variable has been modified.The memory address of
i
is printed using the&
operator, showing the location in memory where the variable is stored.
Last updated