Introduction
Hey Ninjas! Do you know Google launched a new programming language this year? Yes, and they call it Carbon. Carbon is a successor language of C++. Carbon is a language introduced in July 2022. You must have heard the name Pointers, which is common in most programming languages.
Today we will discuss the topic of Pointers in Carbon. Let's start without wasting time.
Pointers
A pointer is a variable that stores the address of memory. And the value is the address of the other variable of the same data type. The * operator is used to dereference the variable's value that the pointer points to.
Here, in the left section (In the code), we assigned a value of 10 to the variable x. Then the x went to the memory address 12 and stored the value 10 to it. Now we again assign a pointer variable pointing to the address of x. Now it stores the address of x in the memory, as shown in the figure above.
Syntax
Syntax to declare any Pointers in Carbon is
var p: i32* = &*x;
Here,
-
p is the variable name.
-
i32* is the return type of variable p.
- x is the value whose address will be stored in the variable p.
Example 1
Let's take a simple example that will clear all your doubts about Pointers in Carbon.
package NinjaTest api;
fn Main() -> i32 {
var x: i32 = 5;
x = 10;
var p: i32* = &x;
*p = 8;
Print("Value of x: {0}", x);
return 0;
}
Output:
Explanation
Now we will discuss the example code. Let's start.
In the above code,
-
First, we entered the main function.
-
Then, we declared a variable x and assigned it a value of 5.
-
In the next step, we explicitly changed the value of x from 5 to 10.
-
Now we declared a variable p of type pointer and assigned it the address of x (&x).
-
Next, we changed the value of pointer p to 8.
- And at the end, we printed the value of x.
Example 2
Let's take one more simple example that will clear all your doubts about Pointers in Carbon.
package NinjaTest api;
fn Main() -> i32 {
var x: i32 = 8;
x = 15;
Print("---");
Print("x = {0}", x);
var y: i32* = &x;
*y = 10;
Print("---");
Print("x = {0}", x);
Print("y = {0}", *y);
var z: i32* = &*y;
*z = 5;
Print("---");
Print("x = {0}", x);
Print("y = {0}", *y);
Print("z = {0}", *z);
return 0;
}
Output:
Explanation
In the above code,
-
First, we entered the main function.
-
Then, we declared a variable x and assigned it a value of 8.
-
In the next step, we explicitly changed the value of x from 8 to 15.
-
Now we printed the value of x.
-
We declared a pointer variable y, and this time we assigned it the address of x.
-
Now, we set the value 10 to the pointer of y.
-
Next, we printed the value of both x and y. Here, the value of both variables will be changed to 10. The reason is we have stored the value 10 to the pointer of y where y is the address of x, so it will change the value of y and x to 10.
-
Now, we have again declared a pointer variable z and assigned it the address of pointer y.
-
We set the value 5 to the pointer of z.
- In the end, we printed the value of x, y, and z.