Comparison of Modern C++ and Apple’s Swift Programming Language Syntax

This is a guest post from Bradley Needham, one of my DevelopMentor colleagues. He manages our C++ curriculum and was inspired by my Swift / Python comparison (Comparison of Python and Apple’s Swift Programming Language Syntax).

Here’s Bradley and C++ vs. Swift. Thanks Bradley!


When Michael wrote his Python vs Swift article, I found it interesting how similar each of these languages (Python, C#, and Swift) are and thought it might be worth having a similar article comparing Modern C++ and Swift.

Code Comments

Swift has the same comments as C++ with a twist:

// C++ single line comment
// Swift single line comment

/* C++ Multiline
comment but cannot nest */

/* Swift Multiline
comment but /*can*/ nest */

Constants and Variables

Swift is strictly typed but also makes use of type inference. C++ is also strictly typed and makes use of type inference.

var age = 25 // An inferred initialized Int variable in Swift
var salary : Float // An explicit uninitialized Float in Swift

auto age = 25; // An inferred initialized int variable in C++
double salary; // An explicit uninitialized float in C++

let pi = 3.1415 // Constant in Swift

const auto pi = 3.1415; // Constant in C++

Strings

Swift treats double-quoted literals as the String type. C++ treats double-quoted literals as a zero-terminated const char[] but does have a standard string type that can be used.

var msg = "A String in Swift"
var s = msg.utf16Count // s is 17

auto msg = "A zero-terminated const char[] in C++";
auto s = msg.length(); // error no such member

auto msg1 = std::string("A string in C++");
auto s = msg.length(); // s is 15

Both Swift and C++ support unicode. Swift provides the String type and C++ std::u16string.

Arrays

Swift supports dynamically-growable arrays. C++ has std::vector which offers similar functionality.

Declaring

// Swift
var nums = [1,2,3,5,7,11]
var strings = ["hello", "how are you", "goodbye"]

// C++
auto nums = std::vector {1,2,3,5,7,11};
auto strings = std::vector {"hello", "how are you", "goodbye"};

Using

Here is a comparison of using arrays in the two languages.

// Iteration in Swift
var nums = [1,2,3,5,7,11]
for n in nums {
println(n)
}

// Iteration in C++
auto nums = std::vector<int>{1,2,3,5,7,11}<wbr />;
for (auto n : nums) {
std::cout << n << "n";
}

// Updating values
nums[2] = 10 // Swift
nums[2] = 10 // C++

// Check for elements
// Swift
if !nums.isEmpty {
println("nums is not empty")
}

// C++
if (!nums.empty()) {
std::cout << "nums is not emptyn";
}

// Adding items
nums.append(7) // Swift
nums.push_back(7) // C++

Dictionaries

Swift has build in support for dictionaries. C++ has std::map and std::unordered_map.

// Swift
var cust = ["name": "Brad", "state": "CA"] // initialize

var the_name = cust["name"] // access value
cust["name"] = "Bradley" // change value
cust["hobby"] = "Swimming" // add key/value
cust.removeValueForKey("hobby") // remove key/value

// C++
auto cust =
std::map<std::string, std::string> {{"name", "Brad"}, {"state", "CA"}};

auto the_name = cust["name"]; // access value
cust["name"] = "Bradley"; // change value
cust["hobby"] = "Swimming"; // add key/value
cust.erase(cust.find("hobby")); // remove key/value

Both languages also allow for checking for the existence of a key

// Swift
if let theHobby = cust["hobby"] {
println("Your hobby is (theHobby)")
}

// C++
try {
auto theHobby = cust.at("hobby");
std::cout << "Your hobby is " << theHobby << “\n";
} catch (...) {
}

// C++
auto it = cust.find("hobby");
if (it != cust.end()) {
std::cout << "Your hobby is " << it->second << “\n";
}

Conditional statements

Swift allows the removal of parenthesis, C++ requires them.

// Swift
var n = 42
if n < 40 {
println("n is less than 40")
} else {
println("n is 40 or above")
}

if (n == 42) { // works with or without parenthesis
println("the answer")
}

// C++
if (n < 40) { // must have parenthesis
println("n is less than 40")
} else {
println("n is 40 or above")
}

if (n == 42) {
println("the answer")
}

// conditional and logic operators are the same
// &&, ||, <=, >=, !, ==, etc.

Switch statements

Default behavior differs between languages. At the end of a case statement, Swift has an automatic break while C++ falls through to next case.

// Swift
switch (i)
{
case 1:
// do work
case 2:
// do work
default:
// do work
}

// C++
switch (i)
{
case 1:
// do work
break; // must explicity break out of switch
case 2:
// do work
break; // must explicity break out of switch
default:
// do work
break; // must explicity break out of switch
}

fallthrough keyword is used to fall through a case in Swift. In C++, removal of the break causes a fall through

// Swift
switch i
{
case 1:
// do work
case 2:
// do work
fallthrough // must explicity fall through
default:
// do work
}

// C++
switch (i)
{
case 1:
// do work
break; // must explicitly break out of switch
case 2:
// do work
// no break will fall through
default:
// do work
break; // must explicitly break out of switch
}

Swift allows for switching on Strings, C++ does not

// Swift only
switch str
{
case "hello":
// do work
case "goodbye":
// do work
default:
// do work
}

Swift allows for range cases. C++ uses the default fall through to accomplish similar functionality

// Swift
switch i
{
case 1...3:
// do work
default:
// do work
}

// C++
switch (i)
{
case 1:
case 2:
case 3:
// do work
break;
default:
//do work
break;
}

Functions

Both languages have rich support for functions, including lambdas, function objects, and tuples.

// Swift
func getUser(id : Int) -> (String, String) {
var username = "username"
var email = "email"
return (username, email)
}

var (n, e) = getUser(1) // n = username, e = email

// C++11
auto getUser(int id) -> std::tuple<std::string, std::string> {
auto username = "username";
auto email = "email";
return std::make_tuple(username, email);
}

// C++14
auto getUser(int id) {
auto username = "username";
auto email = "email";
return std::make_tuple(username, email);
}

std::string n, e;
std::tie(n, e) = getUser(1);

Conclusion

Most modern 3rd-generation languages have many similarities, it just takes getting use to the small differences in order to be able to code between them. Once you get past the language issues, you can spend your time on the platform API which is the thing that really lets you get your work done.

15 comments

  • I like this article. At long last, someone doesn’t treat modern C++ like some weird, 80’s-era language.

    C++14 now has a string literal suffix, so the code in the strings section can be shortened to:


    auto my_string = "Code here"s;

    Note the s at the end.

  • The main difference lies in OOPs with smalltalk (dynamic dispatch/late binding) adopted by swift/O-C vs. simula(static/virtual binding only) style adopted by C++. Then there is ARC for memory management.

    • Thanks for the comment. I’m not sure that swift users dynamic dispatch. I believe it’s fully statically typed. But that is true for ObjC.

  • swift unless sub-classed using an NSObject type behaves with static binding.I am told it does have a vtable of sorts.If suclassed with NSObject, the runtime opts for dynamic dispatch

  • Quora
  • I think this article focuses on syntactic details but not on he high level design philosophy of each language.

    Swift tries really hard through its design to help programmers avoid the most common pitfalls of the C++ programmer: bad pointer dereferencing, buffer overflows, memory leaks / explicit memory management, goto fail style bugs… all this while compiling down to similarly efficient machine code.

    This, along with the much reduced need for boilerplate (include guards, header files, semicolons…) is what’s most notable about the language.

  • Although I appreciate this little cheery comparison, it completely disagree with the conclusion. First, even if the basic constructs of those modern languages tend to be similar (due to the long competition causing a long-term convergence) the dissimilarities are vast, both in how the languages work, and in little-beyond-basic code. While template hell in C++ and the use of lambdas and extensive use of generics, make your code very hard to debug, as lots of code simply isn’t there – it’s auto generated for you from templates by the compiler, Swift had those notions of tuples and code-blocks and multi-type switches etc. deep in their original design, hence they let you work and debug your code much easier. Their syntax is not the patch-on-patch we came to get used to, growing with C++. It makes much more sense, and it is not so obscure.

    What kind of human could tell you why in the following line:

    auto destURLGuard = RAII::guard([destURL](){Q_CFRELEASE(destURL);});
    

    one must put the destURL in brackets? and what human would guess the need for them?

    Also, swift, like C++, come with a big set of design patterns in mind, and overall concept of the “swifty” way to do things. To really compare C++ and swift, you’d give a good C++ programmer a relatively complex program to write, and give the same definitions to a good swift programmer (and enthusiast, so he/she won’t revert to older paradigms) – then compare the sources.

    That would serve much more meaning to the public.

  • i dont think this author knew exactly c++, why he try to make c++ so dark with his wrong syntax???

Submit a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s