In a myriad of programming languages, do we really need another one? According to Google, the answer is yes.
With the intention of succeeding in C++, a few days back Google launched Carbon as the next generation of programming language. It is an open-source project that is still in the testing stage. The Carbon language, which was first presented by Chandler Carruth(a software engineer at Google) at the CppNorth conference, appears to be a fantastic substitute for C++.
Now, the question is can Carbon prove to be a successor to C++?
In this article, we will learn about several features of the Carbon language and afterward dive right into its fundamental syntax with some sample code.
Let's dive in!
What is Carbon Language?
Carbon is intended to be as analogous to C++ as TypeScript is to JavaScript and Kotlin is to Java. Currently, there is no in-work Carbon compiler or toolchain, although a sample interpreter for Carbon is available.
Both the C and C++ legacies are not carried over into Carbon. Instead, the creators made sure that Carbon's development was far more effective. It is also constructed using open-source methodologies, procedures, and tools. It was created from the ground up using features of current concepts like generics, modular code, consistency, and simple syntax.
Carbon is an open-source language, so its developers want it to succeed as "an autonomous and community-driven initiative." As a result, GitHub will be used for project maintenance, and Discord for communication.
Why build Carbon?
C++ is having difficulty upgrading and addressing developers' demands, in large part as a result of accruing years' worth of technological debt. It is exceedingly difficult to incrementally improve C++ because of the technical debt it has accrued as well as difficulties with its evolution process.
Safety, and particularly memory safety, is still a major issue for C++ and something that a replacement language must solve. The initial attention and concentration of carbon is on taking care of crucial, low-hanging fruit in the safety domain right away.
Carbon is launched to overcome the problems of C++; C++ is falling short on some of its objectives, such as those related to performance-critical software, syntax and software advancement, code that is simple to read and write, quick and scalable development, and others, are not being met.
So it is like a successor to C++ similar to:
C -> C++
JavaScript -> TypeScript
Objective-C -> Swift
Java -> Kotlin
C++ -> Carbon Language
Objectives and Features of Carbon
- Performance-critical software
- Software and language evolution
- Code that is easy to read, understand, and write
- Practical safety and testing mechanisms
- Fast and scalable development
- Modern OS platforms, hardware architectures, and environments
- Interoperability with and migration from existing C++ code
Carbon VS Rust (Carbon in, Rust out!)
The moment before the launch of Carbon, a different programming language Rust, was thought to be C++'s replacement. This was mainly due to the fact that it has syntactic similarities to C++ and offers faster performance and improved memory safety. This is up for debate, though, since many developers considered Rust to be too challenging to master because it also introduced a lot of innovative concepts.
Experts claim that Rust lacks the same degree of two-way interoperability as other technologies, which creates a sort of language barrier when converting between other programming languages.
The introduction keywords and easy grammar of Carbon make it more appropriate than Rust. The function input parameters/arguments of carbon are read-only values while the pointers allow for indirect access and mutation. The programmer can use statements to name types and the package is the root namespace. The programmer can use their package name to import APIs.
While launching Carbon at the event, Chandler also added that Rust, created by Mozilla, lacks the same level of 'bi-directional compatibility' as other technologies. However, Carbon's developers advise developers to continue using Rust if it is both technically and financially feasible for the project.
In addition to the high steep climb, it is difficult to adapt the present C++ codebases of large projects to Rust. The designers of Carbon also claim that it is difficult to switch from C++ to Rust due to the nature of the language. However, Carbon attempts to convert C++ codebases far more effectively than Rust.
Let's get started with the syntax, and examples now that we understand what the Carbon language is and why we should utilize it.
Basic Syntax of Carbon Language with examples
Firstly, you can learn the installation setup of carbon on your system from here After installation, now let's get started on how to use carbon language.
All source code is UTF-8 encoded text. Comments, identifiers, and strings are allowed to have non-ASCII characters.
The following examples may be run using either the online carbon explorer or the Carbon language inspector that you installed in the above step. You may view real-time results by just pasting the samples from below into the online IDE.
Declarations in Carbon
- Functions are declared using the
fn
keyword. - Variables are declared using the keyword
var
. - Variable names must end with
:
followed by a blank space i.e.var x:
. - Constants can be declared using the keyword
let
.- Packages are declared using the keywordpackage
only. .- Comments in Carbon can be declared using two slashes//
same as in C++. - The
auto
keyword can be used to automatically infer the variable type. It can be used in combination withlet
orvar
or as function return types.
Example Code:
package ExplorerTest api;
//fn is function declaration
//return type is i32 i.e. int.
fn Main() -> i32 {
//comment.
var s: auto = "Hello world!"; // Auto Variable
let x: i64 = 23; // Constant
var y: i32 = 6; // Integer variable
Print(s); // Print
return 0; //Return value
}
Functions/Methods in Carbon
As you read above, functions can be declared using the fn
keyword.
The syntax is fn functionName(var param: type ... ) -> return type
Example Code:
package ExplorerTest api;
//For Integer return type
fn add(var a: i32, var b: i32) -> i32 {
return a + b;
}
//For Empty or void return type.
fn PrintCount(var count: i32) {
Print("The count is {0}", count);
}
//Main Function
fn Main() -> i32 {
Print("Sum is {0}", Sum(5, 2));
PrintCount(10);
return 0;
}
Variables in Carbon
- Use the keyword
bool
for booleantrue
orfalse
- Use
i8, i16, i32, i64, i128, i256
for integer type variable. - Use
u8, u16, u32, u128, u256
for unsigned integer types. f16, f32, f64, and f128
something like this can be used for float types._
(underscore) can be used as a digit separator. For Eg: 1_000_000 is still an integer if declared without quotes.
Sample Code:
package ExplorerTest api;
fn Main() -> i34 {
var p: i34 = 1;
var q: i34 = 2;
Print(p + q);
return 0;
}
Strings in Carbon
Strings can be declared via:
- Keyword
String
for the byte sequence. - Use
StringView
as a read-only reference for utf-8 byte sequence.
Also, Strings literals can be declared using:
- For Single Line: Use quotation marks like
(")
- For Multi-Line: Use quotations like
(""")
Sample Code:
fn Main() -> i32 {
var singleline: String = "Hello carbon!";
var multiLine: String = """hello carbonline 1
carbon demo line 2
carbon demo line 3
"""; //End of multi block
return 0;
}
Tuples in Carbon
Tuples are quite as same as in C++, they represent values with multiple coordinates. They can be declared using the parenthesis ( )
.
Sample Code:
package ExplorerTest api;
fn Main() -> i32 {
var x: auto = (0, 1); //tuple
Print("{0}", x[1]);
return x[0];
}
In the above code, (x,y,z)
is a tuple with multiple coordinates. They can be accessed using the index.
Arrays in Carbon
In carbon, arrays are declared using array type and size.
The syntax for the same is [type; size]
For Eg: var xarray: [i32; 4] = (1,2,3,4);
Sample Code:
package ExplorerTest api;
fn Main() -> i32 {
var xarray: [i32; 4] = (0, 1, 5, 6); // array of integer
var index: i32 = 1;
xarray[index] = 0;
Print("{0}", xarray[0]);
Print("{1}", xarray[0]);
return xarray[0] + xarray[1];
}
Conditional Statements in Carbon
Conditional statements are the combination of if
and else
. Similar to C++.
For if-else:
if(condition) {
//statement1
//statement2
//doSomething
} else {
//statement1
//statement2
//doSomething
}
For if-else-if:
if(condition) {
//statement1
//statement2
//doSomething
} else if (condition) {
//doSomething
} else {
//doSomething
}
Sample Code:
package ExplorerTest api;
fn Main() -> i32 {
var x: i32 = 10;
if(x == 10) {
Print("{0} to word is FIVE", x);
} else {
Print("{0} is not known ", x);
}
return 0;
Conclusion
We hope this lesson makes it easier for you to experiment with and comprehend the fundamental ideas and syntax examples in the Google Carbon language. Although this is not the whole list of available syntax, we will cover it in future posts as we continue to explore Carbon's capabilities. Please leave a remark or question in the space provided below.
Happy Learning!!