Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Functions in Carbon Language

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction 

Before we start with discussing the functions in Carbon Language, let us have a glimpse of what exactly Carbon is and why it is being created when there are tons of programming languages in the market. 

So, Carbon is an open-source, statically typed, compiled programming language developed by Google to replace C++. Carbon provides developers with modern programming practices such as generics, modular code organization, and simple syntax. Carbon "is designed around interoperability with C++ as well as large-scale adoption and migration for existing C++ codebases and developers." This would be similar to how Microsoft developed Typescript to improve JavaScript and Kotlin to reinforce Java's weak points. 

Interesting right?

replace me

 

You can refer to below declaration types in Carbon to better write the Code. 

Type 

Keyword

Methods/Functions

fn

Variables

var

Constants

let

Packages

package 

Comments

//

 

This must have given you an idea of what Carbon Language is. If we proceed with the discussion today, we will look at the functions of Carbon and its various types, followed by examples.

Function in Carbon Language

So, let us start:

Functions in Carbon Language 

Functions in Carbon language or any other language are simply a "chunk" of Code you can reuse rather than writing it out multiple times. Functions allow programmers to break down or decompose a problem into smaller chunks, each of which performs a specific task.

As you have read above, functions are declared with the fn keyword. 

Below is the syntax: 

Syntax

fn functionName(var param: type ... ) -> return type

 

Function in Carbon Language

Example 1:

fn Main() -> i32 {
 var s : auto = "Hello Ninja";
 Print(s);
 return 0;
}


Output

output

The above-mentioned code snippet describes the main function and prints some string to the console. If you look carefully, we haven’t provided any parameters to our main function. And yes, that is known as the default functions in Carbon

Let us explore the main function in depth: 

THE MAIN FUNCTION.

We must have often seen the main() function in the code snippets. So, Have you ever thought about the purpose of that function in Carbon or any other programming language? Let’s understand now!

fn Main() -> i32
{
       // main program statements
}


Need for the Main()

The Main() serves as the beginning point for program execution. It handles the program execution by directing the invocation to other functions in the program. 

When the main invokes other functions, it passes execution control to the respective function. The function then returns control to the Main() when the end of the function is reached or a return statement is executed. 

Let us see another example: 

Example 2: Parameterized Functions

package sample api;
fn Square(x: i32) -> i32 {
 return x * x;
}
fn Main() -> i32 {
 return Square(12);
}


Output

output

In the example above, we have a Square function, which takes one parameter and returns its square. 

In the main function, we are invoking the Square function, which is printed on your screen. 

You must be wondering why we haven’t called the main function in Example 1. 

Function in Carbon Language

It is because the language itself defines the main function as the intended beginning of the program. As a result, your operating system (Linux, macOS, Windows, etc.) calls it for you, so you don't need to call it yourself. 

Let us now look at how we can invoke the functions in Carbon: 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Types of Calling Methods 

There are two different types of calling methods in Carbon, like C++: 
 

  1. Call By Value
  2. Call By Reference 

types of calling methods

Call By Value

This method copies the values of the actual parameters into the formal parameters,i.e., the function creates its copy of the argument value and then passes it.

To understand, let us take an example.

Suppose you have been given a juice bottle ( formal parameters ) for testing. You tried, and you liked it. The original bottle ( actual parameters ) is still full, so the juice you drank didn't reflect the original one. 

call_by_value

This is precisely the meaning of Call By Value. Henceforth, any modification in the formal parameter doesn't reflect back to the actual parameters during call-by-value.

Let us see an example to understand the Call by Value better: 

package test api;
fn Sum(var x: i32, var y: i32) -> i32{
   return x + y;
}
fn PrintSum(var x: i32, var y: i32){
   x = 0;
   Print(Sum(x,y));
}
fn Main() -> i32{
   var a: auto = 1;
   PrintSum(a,2);
   Print(a);
   return 0;
}


Output

output

Explanation: In the above example, we are finding the sum of two variables which are x and y. 

  • The value of a set to 1 in the main function.
     
  • We have another function, named Sum , that is finding the sum of two variables.
     
  • Last, we have the PrintSum function which is printing the values. 
     
  • Since the call by value is employed, the changed value inside the function must not reflect the original value. 
sample code

Let us now have a look at Call By Reference method:
 

Call By Reference

As the name indicates, a reference to the original variable is passed rather than passing a value to the function being invoked. 

  • When a function is invoked by reference, the formal parameters become references to the actual parameters. 
     
  • This means that the invoked function does not create its copy of original values; rather, it refers to the original values only by different names, i.e., the references. 
     
  • Henceforth, the invoked function works with the original values, and any alteration in the values gets reflected back to the original one.

call by reference

To understand the call by Reference concept, you must be familiar with Pointers in Carbon. 

What are Pointers?

A pointer is a type of variable that holds the memory address of another type of variable as its value. 

  • To declare a pointer put * after the type.
  • To dereference put * before the variable name.
  • To get the address of a variable, put & before the variable name.


Now, let us see an example of Call By Reference:

In the example below, there is a function named Increment which is incrementing the value of x by 1. Since we are applying a call by reference technique, the output must return the updated or reflected result performed by the function. 

package test api;
fn Increment(var x: i32*){
   // incrementing the x by 1
   *x = *x + 1;
}
fn Main() -> i32{
  var a: auto = 1;
  // call by reference
  Increment(&a);
  Print("{0}", a);
  return 0;
}


Output

output

So far we have discussed Functions in Carbon, let us now have a look at some faqs based on the above discussion. 

Frequently Asked Questions

When was the Carbon language introduced?

Carbon language was introduced in July 2022 by a Google engineer.

Is Carbon language Bi-directional?

Carbon language is Bi-directional as it allows us to call C++ language code from Carbon and also Carbon language code to C++.

Why is Carbon an open-source language?

The open-source approach is very effective and successful for languages like Carbon. It is important to have a broad community working on improving it. The project is developed in such a way to be contributed by both small and large players.

How are variables declared in Carbon?

Variables are declared with the var keyword. The is used after the variable names. Example: var x: i32 = 7. The integer type is specified by i32 in this example.

Conclusion 

To conclude the discussion, we explored Functions in Carbon Language. We have also looked at types of functions in Carbon Language. At last, we have looked at types of function invocation techniques with examples. 

If you want to enhance your knowledge on Carbon language, you can check out our other articles-

👉 Data types in Carbon

👉 Variables in Carbon

👉 Strings in Carbon

👉 Data Types in C++

You can refer to our guided paths on the Coding Ninjas Studio platform to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. To practise and improve yourself in the interview, you can also check out Top 100 SQL problemsInterview experienceCoding interview questionsand the Ultimate guide path for interviews. Do upvote our blog to help other ninjas grow.

Topics covered
1.
Introduction 
2.
Functions in Carbon Language 
3.
Types of Calling Methods 
4.
Frequently Asked Questions
4.1.
When was the Carbon language introduced?
4.2.
Is Carbon language Bi-directional?
4.3.
Why is Carbon an open-source language?
4.4.
How are variables declared in Carbon?
5.
Conclusion