<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ C++ - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ C++ - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 05 Jun 2026 20:27:22 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/cpp/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ A Brief Introduction to SQLite ]]>
                </title>
                <description>
                    <![CDATA[ SQLite is one of the most underappreciated tools in a developer's toolkit. It's a full-featured relational database that runs directly in your application. No server setup. No configuration files. No network protocols. Just a simple library that give... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-brief-introduction-to-sqlite/</link>
                <guid isPermaLink="false">68cd625e82b856dadd4cceba</guid>
                
                    <category>
                        <![CDATA[ SQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQLite ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Mark Mahoney ]]>
                </dc:creator>
                <pubDate>Fri, 19 Sep 2025 14:02:06 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1758290415152/439fa61c-9342-47cb-867a-0416fe6bd6cf.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><a target="_blank" href="https://sqlite.org/">SQLite</a> is one of the most underappreciated tools in a developer's toolkit. It's a full-featured relational database that runs directly in your application. No server setup. No configuration files. No network protocols. Just a simple library that gives you the power of an ACID compliant RDBMS right where you need it.</p>
<p>SQLite powers more applications than you might think. It's in every smartphone, most web browsers, and countless desktop applications. Your phone probably has hundreds of SQLite databases on it right now. Despite handling billions of databases worldwide, many developers aren't familiar with all of the cool things that you can do with SQLite.</p>
<p>This tutorial introduces SQLite through practical examples in C/C++, Python, and Java. You can pick and choose the languages that suit your needs. No language wars here. You'll learn how to integrate SQLite into real applications. Whether you're building a desktop app, a web API, or just need local data storage without the drama of a full database server, SQLite has your back.</p>
<h2 id="heading-code-playbacks">Code Playbacks</h2>
<p>Code playbacks are a unique way to learn about programming. They are guided walkthroughs of code, allowing you to see not just the code itself but also the thought process behind it. This approach helps you understand not only what the code does, but why it was written that way. Here is a short video to show how to move through a code playback:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/uYbHqCNjVDM" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>By registering on <a target="_blank" href="https://playbackpress.com/books">Playback Press</a>, you'll gain access to an AI assistant that can answer your questions about the code. This makes learning even more interactive and personalized. Watch this video to see how to work with it:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/WAPql5KZFR4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-a-brief-introduction-to-sqlite">A Brief Introduction to SQLite</h2>
<p>You can find my entire collection of SQLite code playbacks in my free book, <a target="_blank" href="https://playbackpress.com/books/sqlitebook">"Programming with SQLite"</a>.</p>
<p>Here's what you'll learn:</p>
<h3 id="heading-chapter-1-database-design-and-sql">Chapter 1: Database Design and SQL</h3>
<p>In this chapter, I cover the basics of relational database design and SQL. I keep it simple and practical. If you'd like more introductory SQL content like this go to my <a target="_blank" href="https://playbackpress.com/books/sqlbook">Intro SQL</a> book. If you'd like some SQL problems to work through, check out <a target="_blank" href="https://playbackpress.com/books/workedsqlbook">30 Worked SQL Examples</a>. If you already dream in <code>SELECT</code> statements, skip ahead to the chapter that best suits your needs.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/1/1">1.1 Database Design and Basic SQL</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/1/2">1.2 One-to-Many Relationships and More SQL</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/1/3">1.3 Many-to-Many Relationships and Even More SQL</a></p>
</li>
</ul>
<h3 id="heading-chapter-2-sqlite-in-cc">Chapter 2: SQLite in C/C++</h3>
<p>In this chapter, I discuss how to use the low level SQLite API from a C or C++ program. You have a lot of power when using the API and I cover ACID transactions. Yes, we're going to talk about pointers and memory management. Even if you're not a C/C++ programmer and haven't touched a pointer since college, I recommend looking at this chapter. Understanding what's happening under the hood will make the other chapters clearer. Plus, you can impress your friends at parties by casually mentioning you know how database transactions really work.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/2/1">2.1 Using the SQLite C/C++ API</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/2/2">2.2 An Object Oriented Auction Program</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/2/3">2.3 SQLite Transactions</a></p>
</li>
</ul>
<h3 id="heading-chapter-3-sqlite-in-python">Chapter 3: SQLite in Python</h3>
<p>Learn how to use SQLite in any Python program including Flask web apps. No ORMs hiding what's really happening. Just clean, direct database access. I cover how to query and create SQLite databases and then show how to build an API using <a target="_blank" href="https://flask.palletsprojects.com/en/stable/">Flask</a>. By the end, you'll have a working web API that didn't require installing PostgreSQL, configuring connection pools, or sacrificing a weekend to database administration.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/3/1">3.1 Using a SQLite Database in a Python Program</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/3/2">3.2 Creating SQLite Databases</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/3/3">3.3 Using SQLite in a Flask Web Application</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/3/4">3.4 Creating a Web API with Flask and SQLite</a></p>
</li>
</ul>
<h3 id="heading-chapter-4-sqlite-in-java">Chapter 4: SQLite in Java</h3>
<p>In this final chapter I give an example in Java using JDBC. Because sometimes you need to write enterprise code, and SQLite works there too. Who says you need Oracle for everything?</p>
<ul>
<li><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/4/1">4.1 Using a SQLite Database in a Java Program</a></li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Ready to explore SQLite? Start with the first playback and see how fun database programming can be. Each example builds on the previous one, giving you practical experience with real code. Real code solving real problems.</p>
<p>I'd love to hear your thoughts! Feel free to share your comments, questions, or feedback via email: <a target="_blank" href="mailto:mark@playbackpress.com">mark@playbackpress.com</a>. Your input helps me improve and create even better content.</p>
<p>If you've found this tutorial helpful, consider supporting my work through <a target="_blank" href="https://github.com/sponsors/markm208">GitHub Sponsors</a>. Your contributions help cover hosting costs and keep Playback Press free for everyone. Thank you for helping me continue creating educational resources for the developer community!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Embedded Swift: A Modern Approach to Low-Level Programming ]]>
                </title>
                <description>
                    <![CDATA[ Embedded programming has long been dominated by C and C++, powering everything from microcontrollers to real-time systems. While these languages offer unmatched low-level control, they also introduce persistent challenges, manual memory management, u... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/embedded-swift-a-modern-approach-to-low-level-programming/</link>
                <guid isPermaLink="false">688d5fc7d30be1cecdacf767</guid>
                
                    <category>
                        <![CDATA[ embedded systems ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Firmware Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Swift ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Programming Blogs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ memory-management ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Soham Banerjee ]]>
                </dc:creator>
                <pubDate>Sat, 02 Aug 2025 00:45:59 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754090186842/80a42dca-f2c4-49de-b704-2e90134c6397.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Embedded programming has long been dominated by C and C++, powering everything from microcontrollers to real-time systems. While these languages offer unmatched low-level control, they also introduce persistent challenges, manual memory management, unsafe pointer operations, and subtle logic bugs stemming from weak type systems and undefined behavior.</p>
<p>With the release of Swift 6 and its new Embedded Swift compilation mode, developers now have access to a modern, memory-safe, and performant alternative that’s tailored specifically for resource-constrained systems.</p>
<p>While languages like Rust have also emerged to address these issues, Embedded Swift brings the clarity and safety of Swift to microcontroller environments, without giving up on determinism, binary size, or hardware access.</p>
<p>This article introduces Embedded Swift and explores how it compares to traditional C/C++ development. We’ll cover its key features, programming and memory models, how to set up the toolchain for STM32 microcontrollers, and how to link Swift with existing C drivers.</p>
<p>Along the way, we’ll examine performance trade-offs, growing ecosystem support, and the broader industry movement toward memory-safe languages. As I hope you’ll see, Swift is a serious contender in the future of embedded development.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To get the most out of this article, you should have a basic understanding of programming in Swift and C. Familiarity with embedded hardware platforms and firmware development concepts will also be helpful.</p>
<p>If you're new to embedded systems, consider reviewing this <a target="_blank" href="https://www.freecodecamp.org/news/learn-embedded-systems-firmware-basics-handbook-for-devs/">introductory guide to embedded firmware</a> to build foundational knowledge before diving into Embedded Swift.</p>
<h2 id="heading-scope">Scope</h2>
<p>This article is intended as a practical introduction to Embedded Swift. It covers:</p>
<ul>
<li><p>An overview of Embedded Swift and its key language features</p>
</li>
<li><p>Swift’s programming and memory model in an embedded context</p>
</li>
<li><p>Setting up the Embedded Swift toolchain on macOS for STM32 microcontrollers</p>
</li>
<li><p>Interoperability with C code and linking to existing low-level drivers</p>
</li>
<li><p>A look at memory and instruction-level performance</p>
</li>
<li><p>Future directions and use cases for Embedded Swift</p>
</li>
</ul>
<p>Note that this article does not provide a full tutorial on the Swift language itself. While the primary focus is on STM32, similar principles apply to other supported platforms such as ESP32, Raspberry Pi Pico, and nRF52.</p>
<h2 id="heading-table-of-contents">Table of Contents:</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-swift-what-is-embedded-swift">What is Swift? What is Embedded Swift?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-swift-programming-model">Swift Programming Model</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-swift-memory-management">Swift Memory Management</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-memory-and-instruction-cycle-comparison">Memory and Instruction Cycle Comparison</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-setup-embedded-swift">How to Setup Embedded Swift</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-c-swift-linkages">C-Swift Linkages:</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-future-work">Future Work</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-swift-what-is-embedded-swift">What is Swift? What is Embedded Swift?</h2>
<p>Swift is a modern programming language developed by Apple that combines the performance of compiled languages with the expressiveness and safety of modern language design. While Swift was originally created for iOS and macOS development, it has evolved into a powerful general-purpose language used in server-side development, systems programming, and increasingly, embedded systems.</p>
<p>Embedded Swift is a special compilation mode introduced in Swift 6 that brings the benefits of Swift to resource-constrained platforms like microcontrollers. It lets developers use a safe, high-level language while still producing compact, deterministic, and performant binaries suitable for embedded applications.</p>
<h3 id="heading-key-features-of-swift">Key Features of Swift</h3>
<p>Embedded Swift retains many of the powerful language features that make Swift an attractive alternative to C/C++ in embedded development:</p>
<p><strong>Type Safety</strong>: Swift uses a strong static type system, which prevents many programming errors at compile time. Unlike C, where type mismatches can result in undefined behavior, Swift ensures all types are used correctly before code even runs.</p>
<p><strong>Strict Type Checking</strong>: Swift doesn't allow implicit type conversions that could lose data or cause unexpected behavior. For example:</p>
<pre><code class="lang-swift"><span class="hljs-comment">// This won't compile in Swift</span>
<span class="hljs-keyword">let</span> integer: <span class="hljs-type">Int</span> = <span class="hljs-number">42</span>
<span class="hljs-keyword">let</span> decimal: <span class="hljs-type">Double</span> = <span class="hljs-number">3.14</span>
<span class="hljs-keyword">let</span> result = integer + decimal  <span class="hljs-comment">// Error: Cannot convert value of type 'Int' to expected argument type 'Double'</span>

<span class="hljs-comment">// You must be explicit about conversions</span>
<span class="hljs-keyword">let</span> result = <span class="hljs-type">Double</span>(integer) + decimal  <span class="hljs-comment">// Correct</span>
</code></pre>
<p><strong>Non-nullable Types by Default</strong>: In C, pointers can be null by default, which introduces risk. In Swift, variables cannot be nil unless explicitly marked as optionals:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> name: <span class="hljs-type">String</span> = <span class="hljs-string">"John"</span>
name = <span class="hljs-literal">nil</span>  <span class="hljs-comment">// Compile error - String cannot be nil</span>

<span class="hljs-keyword">var</span> optionalName: <span class="hljs-type">String?</span> = <span class="hljs-string">"John"</span>
optionalName = <span class="hljs-literal">nil</span>  <span class="hljs-comment">// This is allowed</span>
</code></pre>
<h4 id="heading-memory-safety-via-arc-covered-in-detail-later">Memory Safety via ARC (Covered in detail later):</h4>
<p>Swift manages memory automatically using Automatic Reference Counting (ARC). Unlike manual memory management in C/C++, ARC handles object lifecycles efficiently without unpredictable garbage collection pauses. We'll cover ARC and its impact in embedded contexts in a dedicated section later.</p>
<p><strong>Modern Syntax</strong>:<br>Swift's syntax is clean, consistent, and designed for readability. It supports modern paradigms including:</p>
<ul>
<li><p>Functional programming (map, filter, reduce)</p>
</li>
<li><p>Generics (type-safe abstractions)</p>
</li>
<li><p>Protocol-Oriented Programming (discussed in the next section)</p>
</li>
</ul>
<p>These features allow you to write more expressive and maintainable code compared to procedural C or inheritance-heavy C++.</p>
<p><strong>Performance</strong>:<br>Swift is designed to perform on par with C++ in many scenarios. Optimizations such as inlining, dead code elimination, and static dispatch help ensure that high-level abstractions don’t compromise performance. In embedded mode, Swift disables features like runtime reflection and dynamic dispatch to further reduce overhead.</p>
<p>To fully leverage Swift for embedded development, it's important to understand its programming model. Unlike C’s procedural approach or C++’s class-heavy design, Swift promotes protocol-oriented programming and composition, which offers both flexibility and safety in embedded system design.</p>
<h2 id="heading-swift-programming-model">Swift Programming Model</h2>
<p>Swift embraces a multi-paradigm programming model that blends object-oriented, functional, and protocol-oriented programming, all underpinned by strong type safety and memory safety.</p>
<p>For embedded developers coming from C or C++, this model may feel different at first. But it provides a more modular and testable way to build complex systems, something especially valuable in embedded applications where hardware abstraction and strict reliability are critical.</p>
<h3 id="heading-protocol-oriented-programming-pop">Protocol-Oriented Programming (POP)</h3>
<p>Swift emphasizes protocols over inheritance, encouraging developers to define behaviors through protocols and implement them using value types like <code>struct</code> and <code>enum</code>, rather than relying heavily on classes.</p>
<p>This philosophy favors composition over inheritance, allowing you to build complex functionality by combining smaller, well-defined components.</p>
<p>Key Concepts<strong>:</strong></p>
<ul>
<li><p><code>protocol</code> defines required behavior.</p>
</li>
<li><p>Protocol extensions provide default behavior.</p>
</li>
<li><p>Prefer value semantics using <code>struct</code>.</p>
</li>
</ul>
<p>Example<strong>:</strong></p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">protocol</span> <span class="hljs-title">Speakable</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span>
}

<span class="hljs-class"><span class="hljs-keyword">extension</span> <span class="hljs-title">Speakable</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Default sound"</span>)
    }
}

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Dog</span>: <span class="hljs-title">Speakable</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Woof!"</span>)
    }
}
</code></pre>
<p>Embedded Swift uses protocols with static dispatch. With static dispatch, the compiler knows the exact memory address of the function to call and can generate a direct jump instruction. There's no runtime lookup, no indirection, and no uncertainty.</p>
<h4 id="heading-why-pop-matters-for-embedded-systems">Why POP Matters for Embedded Systems</h4>
<p>First, you get flexible hardware extraction. Protocols make it easy to define interfaces for hardware components, allowing for mock implementations during testing or platform-specific variations.</p>
<p>Second, you have nice low overhead. Embedded Swift uses static dispatch for protocols, meaning there’s no runtime lookup, and calls are resolved at compile time for maximum performance.</p>
<p>Also, <code>struct</code> and <code>enum</code> types avoid heap allocations, making code more efficient and predictable in low-memory environments.</p>
<p>Now that we’ve explored how Swift’s programming model enables safer and more modular embedded code, let’s turn to another critical piece of the puzzle: memory management. Swift’s use of Automatic Reference Counting (ARC) replaces manual memory handling and offers important benefits, and tradeoffs, for embedded systems.</p>
<h2 id="heading-swift-memory-management">Swift Memory Management</h2>
<p>One of Swift’s most impactful features, especially in the context of embedded systems, is its use of Automatic Reference Counting (ARC) for memory management. Unlike C/C++, where memory must be manually allocated and freed using <code>malloc</code> and <code>free</code>, Swift automates this process while maintaining deterministic performance.</p>
<p>This automation significantly reduces the risk of common memory-related bugs like leaks, dangling pointers, or use-after-free errors, all of which are notorious in low-level C code.</p>
<h3 id="heading-how-arc-works">How ARC works</h3>
<p>Swift supports ARC not only for the Cocoa Touch API's but for all APIs, providing a streamlined approach to memory management. Unlike garbage collection systems that can cause unpredictable pauses, ARC works deterministically at compile time and runtime to manage memory.</p>
<p>ARC automatically tracks and manages the lifetime of objects in memory based on how many references point to them.</p>
<ul>
<li><p>Reference Counting: Every object has a counter that tracks how many strong references point to it.</p>
</li>
<li><p>Retain / Release: The compiler inserts <code>retain</code> and <code>release</code> calls automatically during assignment and deinitialization.</p>
</li>
<li><p>Immediate Deallocation: When the reference count reaches zero, the object is deallocated immediately.</p>
</li>
<li><p>Deterministic: Unlike garbage collectors, ARC doesn’t introduce unpredictable pauses or runtime scanning.</p>
</li>
</ul>
<p>Swift offers multiple reference types to give you precise control over memory behavior and prevent cycles:</p>
<p><strong>Strong References</strong> (default)</p>
<ul>
<li><p>Keeps the referenced object alive.</p>
</li>
<li><p>Used in most cases.</p>
</li>
</ul>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MotorController</span> </span>{
    <span class="hljs-keyword">var</span> sensor: <span class="hljs-type">SensorData?</span>  <span class="hljs-comment">// Strong reference</span>

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">updateReading</span><span class="hljs-params">(newData: SensorData)</span></span> {
        <span class="hljs-keyword">self</span>.sensor = newData  <span class="hljs-comment">// Previous sensor data automatically deallocated</span>
    }
}
</code></pre>
<p><strong>Weak References</strong></p>
<ul>
<li><p>Used to break reference cycles (especially in two-way object relationships).</p>
</li>
<li><p>Automatically becomes <code>nil</code> when the referenced object is deallocated.</p>
</li>
</ul>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Device</span> </span>{
    <span class="hljs-keyword">var</span> controller: <span class="hljs-type">MotorController?</span>

    <span class="hljs-keyword">deinit</span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Device deallocated"</span>)
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MotorController</span> </span>{
    <span class="hljs-keyword">weak</span> <span class="hljs-keyword">var</span> device: <span class="hljs-type">Device?</span>  <span class="hljs-comment">// ← Weak reference breaks the cycle</span>

    <span class="hljs-keyword">deinit</span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"MotorController deallocated"</span>)
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">breakCycle</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> device = <span class="hljs-type">Device</span>()
    <span class="hljs-keyword">let</span> controller = <span class="hljs-type">MotorController</span>()

    device.controller = controller
    controller.device = device  <span class="hljs-comment">// ← This is now a weak reference</span>

    <span class="hljs-comment">// When this function ends, both objects are properly deallocated</span>
}

breakCycle()
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Device deallocated</span>
<span class="hljs-comment">// MotorController deallocated</span>
</code></pre>
<p><strong>Unowned References</strong></p>
<ul>
<li><p>Non-optional version of <code>weak</code>.</p>
</li>
<li><p>Assumes the object will never be deallocated while still in use.</p>
</li>
<li><p>More lightweight than <code>weak</code>, but unsafe if misused.</p>
</li>
</ul>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SensorSystem</span> </span>{
    <span class="hljs-keyword">unowned</span> <span class="hljs-keyword">let</span> controller: <span class="hljs-type">MotorController</span>  <span class="hljs-comment">// unowned reference</span>

    <span class="hljs-keyword">init</span>(controller: <span class="hljs-type">MotorController</span>) {
        <span class="hljs-keyword">self</span>.controller = controller
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MotorController</span> </span>{
    <span class="hljs-keyword">var</span> sensorSystem: <span class="hljs-type">SensorSystem?</span>

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">setupSensors</span><span class="hljs-params">()</span></span> {
        sensorSystem = <span class="hljs-type">SensorSystem</span>(controller: <span class="hljs-keyword">self</span>)
    }

    <span class="hljs-keyword">deinit</span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"MotorController deallocated"</span>)
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">testUnowned</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> controller = <span class="hljs-type">MotorController</span>()
    controller.setupSensors()
    <span class="hljs-comment">// sensorSystem deallocates before controller ends</span>
}

testUnowned()
<span class="hljs-comment">// Output: MotorController deallocated</span>
</code></pre>
<h3 id="heading-arc-overhead-in-embedded-systems">ARC Overhead in Embedded Systems</h3>
<p>While ARC provides safety benefits, it does introduce some overhead compared to manual memory management:</p>
<h4 id="heading-memory-overhead">Memory Overhead:</h4>
<p>ARC-managed class instances in Swift typically include an additional 4 or 8 bytes to store reference count metadata, depending on the system architecture, 4 bytes on 32-bit systems and 8 bytes on 64-bit systems. This metadata allows the runtime to track how many active references exist to a given object and deallocate it when no references remain. When developers use weak or unowned references, the memory footprint increases further. These references require additional data structures, such as side tables or tracking mechanisms, to manage object liveness and cleanup. In the case of weak references specifically, Swift maintains zeroing weak reference tables that automatically null out pointers once the referenced object is deallocated, ensuring memory safety.</p>
<h4 id="heading-cpu-overhead">CPU Overhead:</h4>
<p>ARC introduces some runtime overhead due to retain and release operations, which are inserted automatically during reference assignments. These operations involve incrementing or decrementing the reference count and are especially common in code that passes objects between functions or stores them in collections. To ensure thread safety, these updates are typically implemented using atomic operations, which add further instruction cycles. In complex object graphs, ARC may also engage in cycle detection and cleanup through the use of weak references to prevent memory leaks caused by strong reference cycles. While Swift's ARC provides deterministic and efficient memory management, it does so with both memory and CPU costs that developers should consider carefully, especially in performance-critical embedded systems.</p>
<h3 id="heading-type-safety-and-error-prevention">Type Safety and Error Prevention</h3>
<p>Swift's type system prevents many common errors that plague C/C++ programs:</p>
<ul>
<li><p><strong>Buffer Overflows</strong>: Swift arrays are bounds-checked, preventing buffer overflow vulnerabilities that are common in C.</p>
</li>
<li><p><strong>Null Pointer Dereferences</strong>: Swift's optional types make null pointer dereferences impossible at compile time.</p>
</li>
<li><p><strong>Use After Free</strong>: Swift's ownership model prevents use-after-free errors that can cause crashes or security vulnerabilities.</p>
</li>
</ul>
<p>Now that we’ve covered Swift's memory model and ARC behavior, let’s explore how it compares to C in terms of memory usage and instruction cycles, a crucial aspect when evaluating Embedded Swift for real-world deployment.</p>
<h2 id="heading-memory-and-instruction-cycle-comparison">Memory and Instruction Cycle Comparison</h2>
<p>Understanding the performance characteristics of Swift versus C is essential for embedded systems, where every instruction cycle and byte of memory matters. While Swift brings advantages like safety and expressiveness, these benefits come with certain trade-offs in terms of memory usage and runtime behavior that embedded developers must evaluate carefully.</p>
<h3 id="heading-memory-management">Memory Management:</h3>
<p>Swift uses Automatic Reference Counting (ARC) to manage memory. ARC tracks the number of references to each object and deallocates it when no references remain. This eliminates the need for explicit <code>free()</code> calls but introduces overhead.</p>
<p>C, in contrast, uses manual memory management. Developers allocate memory using <code>malloc</code> and release it using <code>free</code>, or rely on the stack for most short-lived data.</p>
<p>The table below provides the memory management comparison between Swift and C:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Feature</strong></td><td><strong>Swift (ARC)</strong></td><td><strong>C (Manual)</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Memory strategy</td><td>Automatic reference counting</td><td>Manual with <code>malloc</code>/<code>free</code></td></tr>
<tr>
<td>Overhead per object</td><td>4–8 bytes (for ref count)</td><td>None for stack; variable for heap</td></tr>
<tr>
<td>Deallocation</td><td>Deterministic, triggered by ARC</td><td>Developer-controlled</td></tr>
<tr>
<td>Weak reference support</td><td>Requires additional metadata</td><td>Not built-in</td></tr>
<tr>
<td>Thread safety</td><td>Atomic operations in ARC</td><td>Not guaranteed</td></tr>
<tr>
<td>Layout control</td><td>Limited, compiler-managed</td><td>Full control (via structs/pointers)</td></tr>
</tbody>
</table>
</div><p>Swift ensures safety through deterministic cleanup and predictable memory usage. But this comes at the cost of added memory and CPU overhead.</p>
<p>C’s approach offers complete control over memory layout and minimal runtime cost, but increases the risk of memory leaks and fragmentation without disciplined practices.</p>
<h3 id="heading-instruction-cycle-analysis">Instruction Cycle Analysis</h3>
<p>The safety features in Swift, such as bounds checking, optional unwrapping, and ARC updates, translate into additional CPU instructions. While this can impact performance, the Swift compiler is aggressive about optimization in release builds. For example, inlining and ARC elision can remove much of the overhead in performance-critical paths.</p>
<p>C has no built-in safety checks, allowing it to generate highly efficient, predictable code. Developers can even use inline assembly for tight control over performance.</p>
<p>The table below provides the instruction cycle comparison between Swift and C:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Instruction-Level Feature</strong></td><td><strong>Swift</strong></td><td><strong>C</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Reference count updates</td><td>2–4 instructions per assignment</td><td>N/A</td></tr>
<tr>
<td>Bounds checking</td><td>1–3 instructions per array access</td><td>None</td></tr>
<tr>
<td>Optional unwrapping</td><td>1–2 instructions per check</td><td>N/A</td></tr>
<tr>
<td>Method dispatch</td><td>Protocols introduce indirection</td><td>Direct calls or function pointers</td></tr>
<tr>
<td>Optimization potential</td><td>ARC elision, inlining, dead code removal</td><td>Full manual control, inline assembly</td></tr>
<tr>
<td>Predictability</td><td>High in optimized builds, with some abstraction overhead</td><td>Very high, minimal abstraction</td></tr>
</tbody>
</table>
</div><p>Although Swift inserts extra instructions for safety, much of this cost can be mitigated through compiler optimization.</p>
<p>C has no such features by default, making it ideal for applications where performance must be tightly controlled and the developer is willing to take full responsibility for safety.</p>
<h3 id="heading-instruction-count-comparison-swift-vs-c-loop-performance">Instruction Count Comparison: Swift vs C Loop Performance</h3>
<p>When evaluating Swift and C for embedded use, it's helpful to analyze instruction-level performance on basic operations, such as a loop that processes an array of floating-point numbers. This gives us a concrete sense of the computational cost of each language's safety and abstraction features.</p>
<p>Let’s consider a simple example: summing an array of <code>Float</code> values and returning the average. In Swift, the code uses a high-level <code>for-in</code> loop over an array:</p>
<p>Simple loop performance:</p>
<pre><code class="lang-swift"><span class="hljs-comment">// Swift loop with safety checks</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">processData</span><span class="hljs-params">(<span class="hljs-number">_</span> data: [Float])</span></span> -&gt; <span class="hljs-type">Float</span> {
    <span class="hljs-keyword">var</span> sum: <span class="hljs-type">Float</span> = <span class="hljs-number">0.0</span>
    <span class="hljs-keyword">for</span> value <span class="hljs-keyword">in</span> data {  <span class="hljs-comment">// Iterator with bounds checking</span>
        sum += value     <span class="hljs-comment">// Safe arithmetic</span>
    }
    <span class="hljs-keyword">return</span> sum / <span class="hljs-type">Float</span>(data.<span class="hljs-built_in">count</span>)  <span class="hljs-comment">// Safe division</span>
}
<span class="hljs-comment">// Estimated: ~8-10 instructions per iteration</span>
</code></pre>
<p>Although elegant and safe, this loop includes several safety mechanisms:</p>
<ol>
<li><p>Bounds checking on every array access</p>
</li>
<li><p>Reference counting if <code>data</code> is passed as a reference type</p>
</li>
<li><p>Overflow protection in debug mode</p>
</li>
<li><p>Optional handling or runtime checks if <code>data</code> might be empty</p>
</li>
</ol>
<p>These checks introduce runtime overhead, resulting in an estimated 8–10 instructions per iteration on most platforms (depending on optimization level and target architecture). In release builds, Swift aggressively inlines and strips redundant checks, but some level of abstraction cost remains, especially compared to raw memory access in C.</p>
<p>Now, compare that to its equivalent in C:</p>
<pre><code class="lang-c"><span class="hljs-comment">// C loop without safety checks</span>
<span class="hljs-function"><span class="hljs-keyword">float</span> <span class="hljs-title">process_data</span><span class="hljs-params">(<span class="hljs-keyword">float</span>* data, <span class="hljs-keyword">int</span> count)</span> </span>{
    <span class="hljs-keyword">float</span> sum = <span class="hljs-number">0.0f</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; count; i++) {  <span class="hljs-comment">// Direct pointer arithmetic</span>
        sum += data[i];                <span class="hljs-comment">// Direct memory access</span>
    }
    <span class="hljs-keyword">return</span> sum / count;  <span class="hljs-comment">// Direct division (no safety check)</span>
}
<span class="hljs-comment">// Estimated: ~4-5 instructions per iteration</span>
</code></pre>
<p>This version performs direct memory access with pointer arithmetic, no bounds checks, and no type safety. The C code is lower-level, with fewer runtime checks, and compiles down to just 4–5 instructions per iteration, depending on the target CPU and compiler flags. It is lean and fast, ideal for cycles-per-instruction-critical scenarios.</p>
<p>The table below shows the comparison of single loop performance between Swift and C:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Aspect</td><td>Swift</td><td>C</td></tr>
</thead>
<tbody>
<tr>
<td>Array access</td><td>Bounds-checked</td><td>Direct pointer access</td></tr>
<tr>
<td>Loop iteration</td><td>High-level iterator abstraction</td><td>Raw loop with pointer increment</td></tr>
<tr>
<td>Instruction count (per loop)</td><td>~8–10 (in debug), ~6–8 (in release)</td><td>~4–5</td></tr>
<tr>
<td>Division</td><td>Safe (avoids divide-by-zero in dev)</td><td>Direct</td></tr>
<tr>
<td>Overflow behavior</td><td>Checked in debug, unchecked in release</td><td>Unchecked</td></tr>
<tr>
<td>Readability and safety</td><td>High</td><td>Low</td></tr>
<tr>
<td>Performance</td><td>Lower (but optimizable)</td><td>Higher (manual)</td></tr>
</tbody>
</table>
</div><p>Now that we’ve compared Swift and C in terms of memory and cycle costs, let’s move into the practical side: how to set up Embedded Swift on an STM32 platform and get started with real-world development.</p>
<h2 id="heading-how-to-setup-embedded-swift">How to Setup Embedded Swift</h2>
<p>In this section, we'll walk through how to configure and use Embedded Swift for development on STM32 microcontrollers. STM32 is a popular family of ARM Cortex-M–based microcontrollers, commonly used in industrial, consumer, and IoT applications.</p>
<h3 id="heading-prerequisites-1">Prerequisites</h3>
<p><strong>Required Software:</strong></p>
<ul>
<li><p>Swift Development Snapshot (includes the Embedded Swift toolchain)</p>
</li>
<li><p>Swiftly - Easiest way to manage and install swift toolchains</p>
</li>
<li><p>Swiftc - Swift Compiler command-line tool</p>
</li>
<li><p>Python3 - Required to run scripts to convert Mach-O to binary files</p>
</li>
<li><p>Git (to clone sample repositories) like <a target="_blank" href="https://github.com/swiftlang/swift-embedded-examples">https://github.com/swiftlang/swift-embedded-examples</a></p>
</li>
<li><p>A Unix-like development environment (macOS is currently best supported)</p>
</li>
</ul>
<p><strong>Target Hardware:</strong> This guide focuses on STM32 microcontrollers, which are widely used in embedded applications and have excellent community support.</p>
<p>This guide walks you through the full setup process, from installing the required Swift toolchain to flashing the final binary onto your board. We’ll begin by installing the Swift Development Snapshot using Swiftly, a simple command-line utility for managing Swift toolchains. From there, we’ll configure the build system, set up the correct board variant, customize the build script, and compile the Swift and C source code into a binary. Finally, we’ll flash the firmware onto the STM32 using standard tools</p>
<h3 id="heading-install-swift-development-snapshot">Install Swift Development Snapshot</h3>
<p>The easiest way to install and manage Embedded Swift toolchains is by using the swiftly tool, which simplifies downloading and using Swift snapshots.</p>
<h4 id="heading-macos-installation">macOS Installation:</h4>
<p>The below steps will help install the Swift embedded toolchain:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Using Swiftly (Recommended)</span>
curl -O https://download.swift.org/swiftly/darwin/swiftly.pkg
installer -pkg swiftly.pkg -target CurrentUserHomeDirectory
~/.swiftly/bin/swiftly init --quiet-shell-followup
<span class="hljs-built_in">source</span> <span class="hljs-string">"<span class="hljs-variable">${SWIFTLY_HOME_DIR:-<span class="hljs-variable">$HOME</span>/.swiftly}</span>/env.sh"</span>

<span class="hljs-comment"># Install and use development snapshot</span>
swiftly install main-snapshot
swiftly use main-snapshot

<span class="hljs-comment"># Verify installation</span>
swift --version
</code></pre>
<p>You can clone this Github example repository:</p>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> https://github.com/swiftlang/swift-embedded-examples.git 
<span class="hljs-built_in">cd</span> swift-embedded-examples/projects/stm32-blink
</code></pre>
<p>The stm32-blink contains:</p>
<ul>
<li><p>Swift code that toggles GPIOs</p>
</li>
<li><p>A C startup file with vector table</p>
</li>
<li><p>A build.sh script that uses swiftc, clang, and a custom linker setup</p>
</li>
</ul>
<h3 id="heading-setup-the-stm32-board">Setup the STM32 Board</h3>
<p>Tell the build script which STM32 board is being used:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">export</span> STM_BOARD=STM32F746G_DISCOVERY
</code></pre>
<p>You can add your own board variant by defining the appropriate memory map and compiler flags in the script.</p>
<h3 id="heading-modify-buildsh-optional">Modify build.sh (Optional)</h3>
<p>Ensure the script correctly locates the following:</p>
<ul>
<li><p>swiftc: should point to the toolchain you installed with Swiftly</p>
</li>
<li><p>clang: can be macOS’s default Clang</p>
</li>
<li><p>libBuiltin.a, crt0.s, and macho2bin.py: used to provide minimal runtime support and convert output to flashable binaries</p>
</li>
</ul>
<p>If needed, update these paths:</p>
<pre><code class="lang-bash">SWIFT_EXEC=<span class="hljs-variable">${SWIFT_EXEC:-$(swiftly which swiftc)}</span>
CLANG_EXEC=<span class="hljs-variable">${CLANG_EXEC:-$(xcrun -f clang)}</span>
PYTHON_EXEC=<span class="hljs-variable">${PYTHON_EXEC:-$(which python3)}</span>
</code></pre>
<p>Ensure the linker flags match your target’s flash and RAM sizes.</p>
<h3 id="heading-build-and-flash-the-project">Build and Flash the Project:</h3>
<p>Run:</p>
<pre><code class="lang-bash">./build.sh
</code></pre>
<p>This compiles Swift and C code, links them, and produces a blink.bin file.</p>
<p>If successful, you’ll see:</p>
<pre><code class="lang-bash">.build/blink.bin  <span class="hljs-comment"># ready to flash Step 6: Flash the Firmware to STM32</span>
</code></pre>
<p>Use ST-Link tools or openocd to flash your board. Example using st-flash:</p>
<pre><code class="lang-bash">brew install stlink
st-flash write .build/blink.bin 0x8000000
</code></pre>
<p>You should now see an LED blinking.</p>
<p><a target="_blank" href="https://docs.swift.org/embedded/documentation/embedded/stm32baremetalguide">Here’s</a> a more detailed step by step approach to writing a bare metal code on STM32. For comprehensive installation guides covering other platforms (Raspberry Pi Pico, ESP32, nRF52), detailed IDE configuration, troubleshooting, and advanced examples, you can check out the official documentation:</p>
<ul>
<li><p>Complete Setup Guide: <a target="_blank" href="https://docs.swift.org/embedded/documentation/embedded/installembeddedswift/">Install Embedded Swift</a></p>
</li>
<li><p>Platform Examples: <a target="_blank" href="https://github.com/apple/swift-embedded-examples">Swift Embedded Examples Repository</a></p>
</li>
<li><p>Getting Started Tutorial: <a target="_blank" href="https://docs.swift.org/embedded/documentation/embedded">Embedded Swift on Microcontrollers</a></p>
</li>
</ul>
<p>Now that we’ve set up Embedded Swift and explored how to build and run an example project, let’s look at a critical real-world scenario: interfacing Swift with low-level C drivers.</p>
<h2 id="heading-c-swift-linkages">C-Swift Linkages</h2>
<p>In many embedded projects, low-level hardware drivers are written in C because of its close-to-metal control and widespread ecosystem support. Embedded Swift supports seamless interoperability with C, which lets you reuse existing C libraries and drivers, write hardware control logic in C, and implement higher-level application logic in Swift.</p>
<p>This hybrid model lets you combine Swift’s safety and productivity with C’s hardware-level control, with no runtime overhead or object translation.</p>
<p>Let’s walk through an example where a low-level sensor driver is implemented in C and the application logic is written in Swift.</p>
<h3 id="heading-c-header-file-sensordriverh">C Header File (sensor_driver.h):</h3>
<p>This C header file defines the public interface for a low-level sensor driver. It includes standard fixed-width integer types and declares four functions:</p>
<ul>
<li><p>sensor_init(): Initializes the hardware sensor</p>
</li>
<li><p>sensor_read_temperature() and sensor_read_humidity(): Read raw sensor values</p>
</li>
<li><p>sensor_delay_ms(): Delays execution for a given number of milliseconds</p>
</li>
</ul>
<p>This interface acts as a bridge between Swift and C. Swift will link to these functions by name, no wrappers or bindings required.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">ifndef</span> SENSOR_DRIVER_H</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> SENSOR_DRIVER_H</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdint.h&gt;</span></span>

<span class="hljs-comment">// Low-level sensor driver functions</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">sensor_init</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span></span>;
<span class="hljs-function"><span class="hljs-keyword">uint32_t</span> <span class="hljs-title">sensor_read_temperature</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span></span>;
<span class="hljs-function"><span class="hljs-keyword">uint32_t</span> <span class="hljs-title">sensor_read_humidity</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span></span>;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">sensor_delay_ms</span><span class="hljs-params">(<span class="hljs-keyword">uint32_t</span> milliseconds)</span></span>;

<span class="hljs-meta">#<span class="hljs-meta-keyword">endif</span></span>
</code></pre>
<h3 id="heading-c-implementation-sensordriverc">C Implementation (sensor_driver.c):</h3>
<p>This implementation assumes the sensor is memory-mapped at a fixed address (<code>0x40001000</code>). Each register, temperature, humidity, and control, is accessed by offset from that base address.</p>
<p>The <code>sensor_init</code>() function writes <code>0x01</code> to the control register, presumably enabling or starting the sensor hardware.</p>
<p>The <code>sensor_read_temperature()</code> method and <code>sensor_read_humidity()</code> method reads from memory-mapped registers and return the raw ADC values from the sensor.</p>
<p>The <code>sensor_delay_ms()</code> method performs a simple busy-wait loop using nop (no-operation) instructions to approximate a delay. This is suitable for short, coarse-grained delays in bare-metal contexts.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"sensor_driver.h"</span></span>

<span class="hljs-comment">// Hardware register addresses</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> SENSOR_BASE_ADDR    0x40001000</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> TEMP_REG_OFFSET     0x00</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> HUMIDITY_REG_OFFSET 0x04</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> CONTROL_REG_OFFSET  0x08</span>

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">sensor_init</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-comment">// Initialize sensor hardware</span>
    <span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>* control_reg = (<span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>*)(SENSOR_BASE_ADDR + CONTROL_REG_OFFSET);
    *control_reg = <span class="hljs-number">0x01</span>; <span class="hljs-comment">// Enable sensor</span>
}

<span class="hljs-function"><span class="hljs-keyword">uint32_t</span> <span class="hljs-title">sensor_read_temperature</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>* temp_reg = (<span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>*)(SENSOR_BASE_ADDR + TEMP_REG_OFFSET);
    <span class="hljs-keyword">return</span> *temp_reg;
}

<span class="hljs-function"><span class="hljs-keyword">uint32_t</span> <span class="hljs-title">sensor_read_humidity</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>* humidity_reg = (<span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>*)(SENSOR_BASE_ADDR + HUMIDITY_REG_OFFSET);
    <span class="hljs-keyword">return</span> *humidity_reg;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">sensor_delay_ms</span><span class="hljs-params">(<span class="hljs-keyword">uint32_t</span> milliseconds)</span> </span>{
    <span class="hljs-comment">// Simple delay implementation</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">uint32_t</span> i = <span class="hljs-number">0</span>; i &lt; milliseconds * <span class="hljs-number">1000</span>; i++) {
        __asm__(<span class="hljs-string">"nop"</span>);
    }
}
</code></pre>
<h3 id="heading-swift-code-using-c-driver">Swift Code Using C Driver:</h3>
<p>To use these C functions from Swift, you declare them using <code>@_silgen_name</code>, which tells the Swift compiler to link directly to these symbol names at runtime.</p>
<p>The <code>SensorController</code> class encapsulates sensor-related logic. In its <code>init()</code> method, it calls the <code>sensor_init()</code> function defined in C to initialize the sensor hardware.</p>
<p>The <code>readSensors()</code> method reads the raw values from the C driver, converts them into human-readable units using helper functions, stores them internally, and returns the processed values.</p>
<p>The <code>convertTemperature()</code> and <code>convertHumidity()</code> conversion methods apply a basic linear formula to turn raw ADC values into temperature in Celsius and humidity in percentage, respectively. These formulas would be based on the specific sensor’s datasheet.</p>
<p>The <code>checkThresholds()</code> method applies simple threshold logic, a good example of where Swift’s readability and type safety shine. You could easily expand this logic to include error bounds, state machines, or alerts.</p>
<pre><code class="lang-swift"><span class="hljs-comment">// Import C driver functions</span>

<span class="hljs-comment">/*
These declarations match the C function signatures exactly. 
They allow Swift to invoke the C functions as if they were native Swift functions 
— with zero overhead.
*/</span>
@_silgen_name(<span class="hljs-string">"sensor_init"</span>)
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sensor_init</span><span class="hljs-params">()</span></span>

@_silgen_name(<span class="hljs-string">"sensor_read_temperature"</span>)
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sensor_read_temperature</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">UInt32</span>

@_silgen_name(<span class="hljs-string">"sensor_read_humidity"</span>)
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sensor_read_humidity</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">UInt32</span>

@_silgen_name(<span class="hljs-string">"sensor_delay_ms"</span>)
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sensor_delay_ms</span><span class="hljs-params">(<span class="hljs-number">_</span> ms: UInt32)</span></span>

<span class="hljs-comment">// Swift sensor controller using C driver</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SensorController</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> lastTemperature: <span class="hljs-type">Float</span> = <span class="hljs-number">0.0</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> lastHumidity: <span class="hljs-type">Float</span> = <span class="hljs-number">0.0</span>

    <span class="hljs-keyword">init</span>() {
        <span class="hljs-comment">// Initialize the C driver</span>
        sensor_init()
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">readSensors</span><span class="hljs-params">()</span></span> -&gt; (temperature: <span class="hljs-type">Float</span>, humidity: <span class="hljs-type">Float</span>) {
        <span class="hljs-comment">// Read raw values from C driver</span>
        <span class="hljs-keyword">let</span> rawTemp = sensor_read_temperature()
        <span class="hljs-keyword">let</span> rawHumidity = sensor_read_humidity()

        <span class="hljs-comment">// Convert raw values to meaningful units in Swift</span>
        <span class="hljs-keyword">let</span> temperature = convertTemperature(rawValue: rawTemp)
        <span class="hljs-keyword">let</span> humidity = convertHumidity(rawValue: rawHumidity)

        <span class="hljs-comment">// Store for comparison</span>
        lastTemperature = temperature
        lastHumidity = humidity

        <span class="hljs-keyword">return</span> (temperature: temperature, humidity: humidity)
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">convertTemperature</span><span class="hljs-params">(rawValue: UInt32)</span></span> -&gt; <span class="hljs-type">Float</span> {
        <span class="hljs-comment">// Convert raw ADC value to Celsius</span>
        <span class="hljs-keyword">return</span> (<span class="hljs-type">Float</span>(rawValue) * <span class="hljs-number">3.3</span> / <span class="hljs-number">4095.0</span> - <span class="hljs-number">0.5</span>) * <span class="hljs-number">100.0</span>
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">convertHumidity</span><span class="hljs-params">(rawValue: UInt32)</span></span> -&gt; <span class="hljs-type">Float</span> {
        <span class="hljs-comment">// Convert raw ADC value to percentage</span>
        <span class="hljs-keyword">return</span> <span class="hljs-type">Float</span>(rawValue) * <span class="hljs-number">100.0</span> / <span class="hljs-number">4095.0</span>
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">checkThresholds</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">Bool</span> {
        <span class="hljs-comment">// Swift logic for threshold checking</span>
        <span class="hljs-keyword">let</span> tempThreshold: <span class="hljs-type">Float</span> = <span class="hljs-number">25.0</span>
        <span class="hljs-keyword">let</span> humidityThreshold: <span class="hljs-type">Float</span> = <span class="hljs-number">60.0</span>

        <span class="hljs-keyword">return</span> lastTemperature &gt; tempThreshold || lastHumidity &gt; humidityThreshold
    }
}

<span class="hljs-comment">// Main application loop</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">Never</span> {
    <span class="hljs-keyword">let</span> sensorController = <span class="hljs-type">SensorController</span>()

    <span class="hljs-keyword">while</span> <span class="hljs-literal">true</span> {
        <span class="hljs-comment">// Read sensors using Swift controller with C driver</span>
        <span class="hljs-keyword">let</span> readings = sensorController.readSensors()

        <span class="hljs-comment">// Process data with Swift's type safety and expressiveness</span>
        <span class="hljs-keyword">if</span> sensorController.checkThresholds() {
            <span class="hljs-built_in">print</span>(<span class="hljs-string">"Warning: Temperature: \(readings.temperature)°C, Humidity: \(readings.humidity)%"</span>)
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">print</span>(<span class="hljs-string">"Normal: Temperature: \(readings.temperature)°C, Humidity: \(readings.humidity)%"</span>)
        }

        <span class="hljs-comment">// Delay using C driver function</span>
        sensor_delay_ms(<span class="hljs-number">1000</span>) <span class="hljs-comment">// 1 second delay</span>
    }
}
</code></pre>
<p>The <code>func main()</code> is the main event loop standard for embedded systems. It creates the sensor controller, reads sensor data in a loop, checks thresholds, and prints results accordingly. The loop includes a delay (via the C driver) to avoid hammering the sensor continuously.</p>
<p>In an actual embedded context, instead of using <code>print()</code>, you might blink an LED, send UART messages, or log data to memory.</p>
<p>With Embedded Swift and C now working together, let’s explore what lies ahead. The next section outlines ongoing improvements, emerging use cases, and research directions that are shaping the future of Embedded Swift.</p>
<h2 id="heading-future-work">Future Work</h2>
<p>Embedded Swift is still a young but rapidly evolving technology. Its modern language features, type safety, and performance make it an attractive option for embedded development, and ongoing work is expanding its capabilities, reach, and ecosystem.</p>
<h3 id="heading-ongoing-improvements">Ongoing Improvements</h3>
<p><strong>Compiler Optimizations</strong>: The Swift compiler team is actively improving code generation for embedded targets, including:</p>
<ul>
<li><p>Reducing binary size</p>
</li>
<li><p>Minimizing ARC overhead</p>
</li>
<li><p>Improving static dispatch performance</p>
</li>
</ul>
<p><strong>Hardware Support</strong>: Embedded Swift can target a wide variety of ARM and RISC-V microcontrollers, which are popular for building industrial applications. Support for additional architectures is being developed.</p>
<p><strong>Tooling Enhancements</strong>: Tooling support for Embedded Swift is still evolving, but several community-driven and open-source efforts are making development more accessible:</p>
<ul>
<li><p><strong>Build Systems</strong>: The Swift Embedded Working Group provides example projects that adapt Swift Package Manager (SwiftPM) for cross-compilation. Custom linker scripts and build helpers are available for platforms like STM32 and nRF52.</p>
</li>
<li><p><strong>Debugging Support</strong>: Developers can debug Embedded Swift programs using existing tools like GDB or OpenOCD, provided the build includes appropriate debug symbols. While not yet officially streamlined, this approach enables step-through debugging on real hardware.</p>
</li>
<li><p><strong>IDE Integration</strong>: There is no official IDE support yet, but some developers use VSCode with Swift syntax highlighting and external build tasks. These setups are still manual but serve as early prototypes for embedded workflows.</p>
</li>
</ul>
<h3 id="heading-emerging-use-cases">Emerging Use Cases</h3>
<p>There are a number of emerging use cases for embedded Swift. For example, Swift’s memory safety, type guarantees, and protocol-oriented design make it ideal for secure and scalable IoT devices, especially where firmware bugs could affect user safety or privacy.</p>
<p>The automotive sector is also exploring Swift for infotainment systems, driver assistance features, and safety-critical logic (where deterministic execution and safety matter).</p>
<p>Swift’s expressive syntax and compile-time safety make it suitable for industrial automation – think real-time control loops, sensor fusion systems, and edge devices in smart manufacturing.</p>
<p>It’s also useful for medical devices, as it aligns well with strict medical regulations around memory safety, type guarantees, and predictable resource usage.</p>
<h3 id="heading-community-and-ecosystem">Community and Ecosystem</h3>
<h4 id="heading-open-source-projects">Open Source Projects</h4>
<p>The Swift Embedded working group maintains <a target="_blank" href="https://github.com/swiftlang/swift-embedded-examples">example repositories</a> showcasing how to use Embedded Swift on microcontrollers such as STM32, nRF52, and ESP32. Early-stage libraries for UART, GPIO, and basic peripherals are emerging, though the ecosystem is still young compared to C or Rust.</p>
<h4 id="heading-learning-resources">Learning Resources</h4>
<p>While <a target="_blank" href="https://docs.swift.org/embedded/documentation/embedded">Embedded Swift</a> is not yet widely taught in formal curricula, community tutorials and exploratory projects (for example, Swift for Arduino) are lowering the barrier for hobbyists and independent learners. As tooling matures, educational adoption is likely to follow.</p>
<h4 id="heading-industry-interest">Industry Interest</h4>
<p>Embedded Swift is beginning to draw attention from developers and companies looking for safer, more maintainable alternatives to C. Although large-scale adoption remains limited, use cases like rapid prototyping, IoT development, and internal experimentation are gaining traction.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Embedded Swift represents a major step forward in embedded programming. By combining the power and safety of Swift with the low-level control needed for microcontrollers, it offers an exciting alternative to traditional C and C++ development.</p>
<p>While C will remain essential for hardware-level programming and performance-critical paths, Swift brings compelling advantages to many embedded scenarios:</p>
<ul>
<li><p><strong>Memory safety</strong>: Swift eliminates entire categories of bugs such as buffer overflows, use-after-free, and null pointer dereferencing.</p>
</li>
<li><p><strong>Type safety</strong>: Many logic errors are caught at compile time, long before they can cause runtime failures.</p>
</li>
<li><p><strong>Modern language features</strong>: Developers can use functional paradigms, generics, and protocol-oriented design even in embedded code.</p>
</li>
<li><p><strong>C interoperability</strong>: Swift works seamlessly with existing C libraries, allowing gradual adoption without rewriting low-level drivers.</p>
</li>
<li><p><strong>Developer productivity</strong>: Clear syntax, automatic memory management, and strong tooling lead to faster development and easier maintenance.</p>
</li>
</ul>
<p>Government and regulatory bodies are increasingly encouraging or mandating the use of memory-safe programming languages to reduce vulnerabilities in critical software systems. For example:</p>
<ul>
<li><p>In 2022, the <a target="_blank" href="https://media.defense.gov/2025/Jun/23/2003742198/-1/-1/0/CSI_MEMORY_SAFE_LANGUAGES_REDUCING_VULNERABILITIES_IN_MODERN_SOFTWARE_DEVELOPMENT.PDF"><strong>U.S. National Security Agency (NSA)</strong></a> recommended moving away from unsafe languages like C/C++ for new software projects, promoting memory-safe alternatives.</p>
</li>
<li><p>In June 2025, the NSA and CISA released a joint Cybersecurity Information Sheet titled “<a target="_blank" href="https://www.nsa.gov/Press-Room/Press-Releases-Statements/Press-Release-View/Article/4223298/nsa-and-cisa-release-csi-highlighting-importance-of-memory-safe-languages-in-so/">Memory Safe Languages: Reducing Vulnerabilities in Modern Software Development</a>”, which emphasized that memory safety flaws remain a persistent risk, and organizations should develop strategies to adopt memory-safe programming languages in new systems.</p>
</li>
<li><p>The <a target="_blank" href="https://www.trust-in-soft.com/resources/blogs/memory-safety-is-key-the-shift-in-u.s.-cyber-standards"><strong>U.S. Cybersecurity and Infrastructure Security Agency (CISA)</strong></a> and <a target="_blank" href="https://nvlpubs.nist.gov/nistpubs/specialpublications/nist.sp.800-218.pdf"><strong>NIST</strong></a> have echoed similar guidance in the context of national cybersecurity.</p>
</li>
</ul>
<p>While these documents do not mention Swift explicitly, Swift's strong type system, ARC-based memory model, and compile-time safety guarantees align closely with the goals outlined in these recommendations. As such, it offers a practical, developer-friendly path toward safer embedded development.</p>
<p>Swift may not be the right fit for every embedded system. In applications where every byte of memory or instruction cycle is critical, real-time guarantees are hard requirements, or toolchain maturity is essential (for example, RTOS integration, static analyzers), C or Rust may still be preferred.</p>
<p>But in many modern embedded applications, especially those involving rapid prototyping, fast product iteration, safety-critical or maintainable firmware, and interoperability with existing C codebases, Swift offers a highly productive and safe development experience.</p>
<p>Embedded Swift is still maturing, but its momentum is undeniable. With ongoing compiler work, community-driven examples, and growing interest from developers, it’s poised to play a major role in the future of embedded systems.</p>
<p>Whether you're building an IoT device, a piece of industrial equipment, or a proof-of-concept wearable, Swift can help you write safer, more expressive firmware, without giving up performance or control.</p>
<p>Swift can be especially powerful during the prototyping phase, when the primary goal is to validate functionality quickly and safely. And with its increasing support for multiple hardware platforms, it offers a strong foundation for bringing modern software development practices to the embedded world.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Infinite Loops Work in C++ ]]>
                </title>
                <description>
                    <![CDATA[ In C++, a loop is a part of code that is executed repetitively until the given condition is satisfied. An infinite loop is a loop that runs indefinitely, without any condition to exit the loop. In this article, we will learn about infinite loops in C... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-infinite-loops-work-in-c/</link>
                <guid isPermaLink="false">688d43422c35fedc5be4fa94</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                    <category>
                        <![CDATA[ while loop ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Do while loop ]]>
                    </category>
                
                    <category>
                        <![CDATA[ for loop ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ AYUSH MISHRA ]]>
                </dc:creator>
                <pubDate>Fri, 01 Aug 2025 22:44:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754065314765/5c8e45f0-6a43-4f1f-b254-2603b7d37e0c.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In C++, a loop is a part of code that is executed repetitively until the given condition is satisfied. An infinite loop is a loop that runs indefinitely, without any condition to exit the loop.</p>
<p>In this article, we will learn about infinite loops in C++, their types and causes, and their applications.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-infinte-loop-in-c">What is an Infinite Loop in C++?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-infinte-loops-in-c">Types of Infinite Loops in C++</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-common-cause-of-accidental-infinte-loops-in-c">Common Causes of Accidental Infinite Loops in C++</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-application-of-infinte-loops-in-c">Applications of Infinite Loops in C++</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-using-infinite-loops-to-take-user-input-in-c">Using Infinite Loops To Take User Input in C++</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-what-is-an-infinite-loop-in-c">What is an Infinite Loop in C++?</h2>
<p>An infinite loop is any loop in which the loop condition is always true, leading to the given block of code being executed an infinite number of times. They can also be called endless or non-terminating loops, which will run until the end of the program’s life.</p>
<p>Infinite loops are generally accidental and occur due to some mistake by the programmer. But they are pretty useful, too, in different kinds of applications, such as creating a program that does not terminate until a specific command is given.</p>
<h2 id="heading-types-of-infinite-loops-in-c">Types of Infinite Loops in C++</h2>
<p>There are several ways to create an infinite loop in C++, using different loop constructs such as while, for, and do-while loops. Here, we will explore each method and provide examples.</p>
<ul>
<li><p>Infinite While Loops</p>
</li>
<li><p>Infinite For Loops</p>
</li>
<li><p>Infinite do-while Loops</p>
</li>
</ul>
<h3 id="heading-1-infinite-loop-using-while-loop">1. Infinite Loop using While Loop</h3>
<p>This is the most popular type of while loop due to its simplicity. You just pass the value that will result in true as the condition of the while loop.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-plaintext">while(1)
    or
while(true)
</code></pre>
<p><strong>Example Code:</strong></p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Example of Infinite loop in C++ using for loop</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">// Infinite loop using while</span>
    <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"This is an infinite loop."</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>………………….</p>
<h3 id="heading-infinite-loop-using-for-loop">Infinite Loop using For Loop</h3>
<p>In a for loop, if we remove the initialization, comparison, and update conditions, then it will result in an infinite loop.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-plaintext">for(;;)
</code></pre>
<p><strong>Example Code:</strong></p>
<pre><code class="lang-cpp"><span class="hljs-comment">//Example of Infinite loop in C++ using for loop</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">// Infinite loop using for loop</span>
    <span class="hljs-keyword">for</span> (;;) {
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"This is an infinite loop."</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>……………………….</p>
<h3 id="heading-infinite-loop-using-do-while-loop">Infinite Loop using do-while Loop</h3>
<p>Just like the other two loops discussed above, we can also create an infinite loop using a do-while loop. Although this loop is not preferred much due to its longer syntax.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-plaintext">do{
}while(1)
</code></pre>
<p><strong>Example Code:</strong></p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Infinite loop in C++ using do-while loop</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
   <span class="hljs-comment">// infinite do-while loop</span>
    <span class="hljs-keyword">do</span> {
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"This is an infinite loop."</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    } <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>……………………….</p>
<h2 id="heading-common-causes-of-accidental-infinite-loops-in-c">Common Causes of Accidental Infinite Loops in C++</h2>
<p>Infinite loops can be both intentional and accidental. Accidental infinite loops are those which were not intended by the programmer but are caused due to some error in the program.</p>
<p>Following are some of the errors that may cause infinite loops in your programs unintentionally:</p>
<h3 id="heading-1-missing-update-statements">1. Missing Update Statements</h3>
<p>Infinite loops are caused when you forget to add an update condition inside the loop, which will terminate the loop in the future. The following program illustrates such a scenario:</p>
<p><strong>Example Code:</strong></p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Infinite loop caused due to missing update statement</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> i = <span class="hljs-number">3</span>;
    <span class="hljs-keyword">while</span> (i &lt; <span class="hljs-number">5</span>) {
        <span class="hljs-built_in">cout</span> &lt;&lt; i &lt;&lt;<span class="hljs-built_in">endl</span>;
        <span class="hljs-comment">// Missing update: i++;</span>
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>3</p>
<p>3</p>
<p>3</p>
<p>3</p>
<p>3</p>
<p>3</p>
<p>3</p>
<p>……………………</p>
<p>To fix the above code, we can add an update condition inside the loop like this:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// fixed code</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span> ;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">int</span> i = <span class="hljs-number">3</span>;
<span class="hljs-keyword">while</span> (i &lt; <span class="hljs-number">5</span>) {
    <span class="hljs-built_in">cout</span> &lt;&lt; i &lt;&lt; <span class="hljs-built_in">endl</span>;
    i++; <span class="hljs-comment">// add the condition</span>
}

<span class="hljs-keyword">return</span> <span class="hljs-number">0</span> ; 

}
</code></pre>
<p>Output:</p>
<p>3</p>
<p>4</p>
<h3 id="heading-incorrect-loop-conditions">Incorrect Loop Conditions</h3>
<p>The conditions mentioned inside the loop body are crucial to terminate a loop. An incorrect loop condition can result in an infinite loop. The following program illustrates such a scenario:</p>
<p><strong>Example Code:</strong></p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Infinite loop caused due to incorrect loop conditions</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> i = <span class="hljs-number">2</span>;
    <span class="hljs-keyword">while</span> (i &gt;= <span class="hljs-number">0</span>) {  
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Hello AnshuAyush "</span> &lt;&lt; <span class="hljs-built_in">endl</span>;

    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>Hello AnshuAyush</p>
<p>Hello AnshuAyush</p>
<p>Hello AnshuAyush</p>
<p>Hello AnshuAyush</p>
<p>Hello AnshuAyush</p>
<p>……………………..</p>
<p>To fix the above code, we can update <code>i</code> inside the loop to eventually make the condition false:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// fixed code </span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span> ;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">int</span> i = <span class="hljs-number">2</span>;
<span class="hljs-keyword">while</span> (i &gt;= <span class="hljs-number">0</span>) {  
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Hello AnshuAyush"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    i--; <span class="hljs-comment">// loop will stop</span>
}

<span class="hljs-keyword">return</span> <span class="hljs-number">0</span> ; 

}
</code></pre>
<p>Ouptut:</p>
<p>Hello AnshuAyush</p>
<p>Hello AnshuAyush</p>
<p>Hello AnshuAyush</p>
<h3 id="heading-logical-errors-in-the-loop">Logical Errors in the Loop</h3>
<p>In many scenarios, infinite loops are caused by small logical errors in the code. The following program illustrates such a scenario:</p>
<p><strong>Example Code:</strong></p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">3</span>; i &gt;<span class="hljs-number">2</span>; i += <span class="hljs-number">2</span>) {  
        <span class="hljs-built_in">cout</span> &lt;&lt;<span class="hljs-string">"This is an infinite loop"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>This is an infinite loop.</p>
<p>……………………….</p>
<p>To fix the above code, we can either use a decreasing condition or use an incrementing loop condition.</p>
<p>Decreasing condition:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">3</span>; i &gt; <span class="hljs-number">0</span>; i--) {
    <span class="hljs-built_in">cout</span> &lt;&lt;<span class="hljs-string">"This is NOT an infinite loop"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<p>Increasing condition:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">3</span>; i &lt; <span class="hljs-number">10</span>; i += <span class="hljs-number">2</span>) {
    <span class="hljs-built_in">cout</span> &lt;&lt;<span class="hljs-string">"Loop will end when i reaches 10"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<h2 id="heading-applications-of-infinite-loops-in-c">Applications of Infinite Loops in C++</h2>
<p>Infinite loops do not only occur by accident, as I mentioned above. You can also create them on purpose for different use cases. The following are some of the common applications where you might use infinite loops intentionally:</p>
<ul>
<li><p><strong>Event loops:</strong> Many Graphical User Interfaces (GUIs) use infinite loops to keep the program running and responsive to user actions.</p>
</li>
<li><p><strong>Server applications:</strong> Web servers use infinite loops to continuously listen to client connections or requests.</p>
</li>
<li><p><strong>Embedded systems:</strong> Embedded systems, such as microcontrollers, frequently use infinite loops as their main program loops to continuously respond to external events.</p>
</li>
<li><p><strong>User inputs:</strong> Infinite loops are also used to wait for valid user inputs. The loop keeps running until a valid input is provided by the user. We’ll look at an example of this one.</p>
</li>
</ul>
<h3 id="heading-using-infinite-loops-to-take-user-input-in-c">Using Infinite Loops to Take User Input in C++</h3>
<p>Infinite loops are commonly used in scenarios where a program needs to continuously take user input until a specific condition is met, such as exiting the program or getting a valid user input. The following program demonstrates how we can take user input from the user until a specific condition is met:</p>
<p><strong>Example Code:</strong></p>
<pre><code class="lang-cpp"><span class="hljs-comment">// C++ Program to take user input from users using infinite loops</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;string&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">string</span> input;

    <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Enter a command (type 'exit' to quit): "</span>;
        getline(<span class="hljs-built_in">cin</span>, input);

        <span class="hljs-keyword">if</span> (input == <span class="hljs-string">"exit"</span>) {
        <span class="hljs-comment">// Exit the loop if the user types 'exit'</span>
            <span class="hljs-keyword">break</span>; 
        }

        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"You entered: "</span> &lt;&lt; input &lt;&lt; <span class="hljs-built_in">endl</span>;
        <span class="hljs-comment">// Process the input</span>
    }
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Program exited."</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>Enter a command (type 'exit' to quit): Anshu</p>
<p>You entered: Anshu</p>
<p>Enter a command (type 'exit' to quit): Ayush</p>
<p>You entered: Ayush</p>
<p>Enter a command (type 'exit' to quit): exit</p>
<p>Program exited.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Infinite loops aren’t always dangerous. They can be very useful when used with proper control, like break statements or condition checks. But if you use them carelessly, they can crash your program.</p>
<p>So just make sure you check your loop conditions and test your code using print statements between the programs to discover any unexpected behavior. In sum, infinite loops can be very powerful when handled carefully but can be very risky if left unchecked.</p>
<p>And if you'd like to support me and my work directly so I can keep creating these tutorials, <a target="_blank" href="https://paypal.me/ayushM010">you can do so here</a>. Thank you!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Helpful Built-in Functions in C++ that All Devs Should Know ]]>
                </title>
                <description>
                    <![CDATA[ Built-in functions in C++ are those functions that are part of the C++ standard libraries. These functions are designed to provide common and essential functionality that is often required in programming. In this article, we will look at some of the ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/helpful-built-in-functions-in-cpp/</link>
                <guid isPermaLink="false">687fc93c8ff83d5b41883c1e</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ AYUSH MISHRA ]]>
                </dc:creator>
                <pubDate>Tue, 22 Jul 2025 17:24:12 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753105870543/7bdb3c7e-873b-46a2-bdbd-0d881aacedfc.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Built-in functions in C++ are those functions that are part of the C++ standard libraries. These functions are designed to provide common and essential functionality that is often required in programming.</p>
<p>In this article, we will look at some of the most commonly used built-in functions in C++ so you can start using them in your code.</p>
<h3 id="heading-what-well-cover">What we’ll cover:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-the-sqrt-function">The <code>sqrt()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-pow-function">The <code>pow()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-sort-function">The <code>sort()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-find-function">The <code>find()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-binarysearch-function">The <code>binarysearch()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-max-function">The <code>max()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-min-function">The <code>min()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-swap-function">The <code>swap()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-toupper-function">The <code>toupper()</code> Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-tolower-function">The <code>tolower()</code> Function</a></p>
</li>
</ol>
<h2 id="heading-the-sqrt-function">The <code>sqrt()</code> Function</h2>
<p>You use the <code>sqrt()</code> function to determine the square root of the value of type double. It is defined inside the <code>&lt;cmath&gt;</code> header file.</p>
<h3 id="heading-syntax"><strong>Syntax:</strong></h3>
<pre><code class="lang-plaintext">sqrt (n)
</code></pre>
<p><strong>Parameter:</strong> This function takes only one parameter of type double which is a number we want to find the square root of.</p>
<p><strong>Return Type:</strong> The square root of the value of type double.</p>
<h3 id="heading-example-code">Example Code</h3>
<p>Let’s look at an example so you can see how this function works:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// C++ program to see the use of sqrt() function</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cmath&gt;     </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;  </span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;  
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">double</span> x = <span class="hljs-number">100</span>;

    <span class="hljs-keyword">double</span> answer;

    <span class="hljs-comment">// Use the sqrt() function to calculate the square root of the number</span>
    answer = <span class="hljs-built_in">sqrt</span>(x);

    <span class="hljs-comment">// Print the result </span>
    <span class="hljs-built_in">cout</span> &lt;&lt; answer &lt;&lt; <span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>10</p>
<h2 id="heading-the-pow-function"><strong>The</strong> <code>pow()</code> <strong>Function</strong></h2>
<p>You use the <code>pow()</code> function to find the value of the given number raised to some power. This function is also defined inside the <code>&lt;cmath&gt;</code> header file.</p>
<h3 id="heading-syntax-1"><strong>Syntax:</strong></h3>
<pre><code class="lang-plaintext">double pow(double x, double y);
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><p><strong>x:</strong> The base number.</p>
</li>
<li><p><strong>y:</strong> The exponential power.</p>
</li>
</ul>
<p><strong>Return Type:</strong> value of <strong>x</strong> raised to the power <strong>y</strong>.</p>
<h3 id="heading-example-code-1">Example Code:</h3>
<p>Let’s look at an example to see how this works:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// C++ program to see the use of the pow() function</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cmath&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
 <span class="hljs-comment">// Declare an integer variable 'base' </span>
    <span class="hljs-keyword">int</span> base = <span class="hljs-number">5</span>;

<span class="hljs-comment">// Declare an integer variable 'exponent' </span>
    <span class="hljs-keyword">int</span> exponent = <span class="hljs-number">3</span>;

<span class="hljs-comment">// pow(5, 3) means 5^3 which is 5*5*5 = 125</span>
<span class="hljs-comment">// Use the pow() function to calculate base raised to the power of exponent</span>
    <span class="hljs-keyword">int</span> answer = <span class="hljs-built_in">pow</span>(base, exponent);

<span class="hljs-comment">// output the result</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; answer &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<p>Output:</p>
<p>125</p>
<h2 id="heading-the-sort-function">The <code>sort()</code> Function</h2>
<p>The <code>sort()</code> function is part of STL's <code>&lt;algorithm&gt;</code> header. It is a function template that you can use to sort the random access containers, such as vectors, arrays, and so on.</p>
<h3 id="heading-syntax-2">Syntax:</h3>
<pre><code class="lang-plaintext">sort (arr , arr + n, comparator)
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><p><strong>arr:</strong> The pointer or iterator to the first element of the array.</p>
</li>
<li><p><strong>arr + n:</strong> The pointer to the imaginary element next to the last element of the array.</p>
</li>
<li><p><strong>comparator:</strong> The unary predicate function that is used to sort the value in some specific order. The default value of this sorts the array in ascending order.</p>
</li>
</ul>
<p><strong>Return Value:</strong> This function does not return any value.</p>
<h3 id="heading-example-code-2">Example Code:</h3>
<p>Let’s look at an example:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;     </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;    // Header file that includes the sort() function</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;    

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Declare and initialize an integer array with unsorted elements</span>
    <span class="hljs-keyword">int</span> arr[] = { <span class="hljs-number">13</span>, <span class="hljs-number">15</span>, <span class="hljs-number">12</span>, <span class="hljs-number">14</span>, <span class="hljs-number">11</span>, <span class="hljs-number">16</span>, <span class="hljs-number">18</span>, <span class="hljs-number">17</span> };

    <span class="hljs-comment">// Calculate the number of elements in the array</span>
    <span class="hljs-keyword">int</span> n = <span class="hljs-keyword">sizeof</span>(arr) / <span class="hljs-keyword">sizeof</span>(arr[<span class="hljs-number">0</span>]);

    <span class="hljs-comment">// Use the built-in sort() function from the algorithm library</span>
    sort(arr, arr + n);

    <span class="hljs-comment">// Print the sorted array using a loop</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; n; ++i)
        <span class="hljs-built_in">cout</span> &lt;&lt; arr[i] &lt;&lt; <span class="hljs-string">" "</span>;  

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>11 12 13 14 15 16 17 18</p>
<h2 id="heading-the-find-function">The <code>find()</code> Function</h2>
<p>The <code>find()</code> function is also part of the STL <code>&lt;algorithm&gt;</code> library. You use this function to find a value in the given range. You can use it with both sorted and unsorted datasets as it implements a linear search algorithm.</p>
<h3 id="heading-syntax-3"><strong>Syntax:</strong></h3>
<pre><code class="lang-plaintext">find(startIterator, endIterator, key)
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><p><strong>startIterator:</strong> Iterates to the beginning of the range.</p>
</li>
<li><p><strong>endIterator:</strong> Iterates to the end of the range.</p>
</li>
<li><p><strong>key:</strong> The value to be searched.</p>
</li>
</ul>
<p><strong>Return Value:</strong> If the element is found, then the iterator is set to the element. Otherwise, it iterates to the end.</p>
<h3 id="heading-example-code-3">Example Code:</h3>
<p>Let’s look at an example to better understand how it works:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// C++ program to see the the use of the find() function</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;   // Required for the find() function</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;    </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;      </span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;   

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Initialize a vector </span>
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; dataset{ <span class="hljs-number">12</span>, <span class="hljs-number">28</span>, <span class="hljs-number">16</span>, <span class="hljs-number">7</span>, <span class="hljs-number">33</span>, <span class="hljs-number">43</span> };

    <span class="hljs-comment">// Use the find() function to search for the value 7</span>
    <span class="hljs-keyword">auto</span> index = find(dataset.begin(), dataset.end(), <span class="hljs-number">7</span>);

    <span class="hljs-comment">// Check if the element was found</span>
    <span class="hljs-keyword">if</span> (index != dataset.end()) {
        <span class="hljs-comment">// If found, print the position (index) by subtracting the starting iterator</span>
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The element is found at the "</span>
             &lt;&lt; index - dataset.begin() &lt;&lt; <span class="hljs-string">"nd index"</span>;
    }
    <span class="hljs-keyword">else</span> {
        <span class="hljs-comment">// If not found</span>
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Element not found"</span>;
   }
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>The element is found at the 3rd index</p>
<h2 id="heading-the-binarysearch-function">The <code>binary_search()</code> Function</h2>
<p>The <code>binary_search()</code> function is also used to find an element in the range – but this function implements binary search instead of linear search as compared to the <code>find()</code> function. It’s also faster than the <code>find()</code> function, but you can only use it on sorted datasets with random access. It’s defined inside the <code>&lt;algorithm&gt;</code> header file.</p>
<h3 id="heading-syntax-4"><strong>Syntax:</strong></h3>
<pre><code class="lang-plaintext">binary_search (starting_pointer , ending_pointer , target);
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><p><strong>starting_pointer:</strong> Pointer to the start of the range.</p>
</li>
<li><p><strong>ending_pointer:</strong> Pointer to the element after the end of the range.</p>
</li>
<li><p><strong>target:</strong> Value to be searched in the dataset.</p>
</li>
</ul>
<p><strong>Return Value:</strong></p>
<ul>
<li><p>Returns true if the target is found.</p>
</li>
<li><p>Else return false.</p>
</li>
</ul>
<h3 id="heading-example-code-4">Example Code:</h3>
<p>Let’s check out an example to see how it works:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// C++ program for the binary_search() function</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;   </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;    </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;      </span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;   

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Initialize a sorted vector of integers</span>
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; arr = { <span class="hljs-number">56</span>, <span class="hljs-number">57</span>, <span class="hljs-number">58</span>, <span class="hljs-number">59</span>, <span class="hljs-number">60</span>, <span class="hljs-number">61</span>, <span class="hljs-number">62</span> };

    <span class="hljs-comment">// binary_search() works only on sorted containers</span>
    <span class="hljs-keyword">if</span> (binary_search(arr.begin(), arr.end(), <span class="hljs-number">62</span>)) {
        <span class="hljs-comment">// If found, print that the element is present</span>
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-number">62</span> &lt;&lt; <span class="hljs-string">" is present in the vector."</span>;
    }
    <span class="hljs-keyword">else</span> {
        <span class="hljs-comment">// If not found, print that the element is not present</span>
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-number">16</span> &lt;&lt; <span class="hljs-string">" is not present in the vector"</span>;
    }

    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<p>Output:</p>
<p>62 is present in the vector.</p>
<h2 id="heading-the-max-function">The <code>max()</code> Function</h2>
<p>You can use the <code>std::max()</code> function to compare two numbers and find the bigger one between them. It’s also defined inside the <code>&lt;algorithm&gt;</code> header file.</p>
<h3 id="heading-syntax-5">Syntax:</h3>
<pre><code class="lang-plaintext">max (a , b)
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><p><strong>a:</strong> First number</p>
</li>
<li><p><strong>b:</strong> Second number</p>
</li>
</ul>
<p><strong>Return Value:</strong></p>
<ul>
<li><p>This function returns the larger number between the two numbers <strong>a</strong> and <strong>b.</strong></p>
</li>
<li><p>If the two numbers are equal, it returns the first number.</p>
</li>
</ul>
<h3 id="heading-example-code-5">Example Code:</h3>
<p>Here’s an example:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// max() function</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;  </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;   </span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Declare two integer variables</span>
    <span class="hljs-keyword">int</span> a = <span class="hljs-number">8</span> ;
    <span class="hljs-keyword">int</span> b = <span class="hljs-number">10</span> ;

    <span class="hljs-comment">// Use the max() function to find the larger number between a and b</span>
    <span class="hljs-keyword">int</span> maximum = max(a, b);

    <span class="hljs-comment">// Display the result with a meaningful message</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The maximum of "</span> &lt;&lt; a &lt;&lt; <span class="hljs-string">" and "</span> &lt;&lt; b &lt;&lt; <span class="hljs-string">" is: "</span> &lt;&lt; maximum &lt;&lt; <span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>The maximum of 8 and 10 is: 10</p>
<h2 id="heading-the-min-function">The <code>min()</code> Function</h2>
<p>You can use the <code>std::min()</code> function to compare two numbers and find the smaller of the two. It’s also defined inside the <code>&lt;algorithm&gt;</code> header file.</p>
<h3 id="heading-syntax-6">Syntax:</h3>
<pre><code class="lang-plaintext">min (a , b)
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><p><strong>a:</strong> First number</p>
</li>
<li><p><strong>b:</strong> Second number</p>
</li>
</ul>
<p><strong>Return Value:</strong></p>
<ul>
<li><p>This function returns the smaller number between the two numbers <strong>a</strong> and <strong>b.</strong></p>
</li>
<li><p>If the two numbers are equal, it returns the first number.</p>
</li>
</ul>
<h3 id="heading-example-code-6">Example Code:</h3>
<p>Here’s an example:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// use of the min() function</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;  // For the built-in min() function</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;   </span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Declare two integer variables to store user input</span>
    <span class="hljs-keyword">int</span> a = <span class="hljs-number">4</span> ;
    <span class="hljs-keyword">int</span> b = <span class="hljs-number">8</span> ;

    <span class="hljs-comment">// Use the min() function to find the smaller </span>
    <span class="hljs-keyword">int</span> smallest = min(a, b);

    <span class="hljs-comment">// Display the result </span>
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The smaller number between "</span> &lt;&lt; a &lt;&lt; <span class="hljs-string">" and "</span> &lt;&lt; b &lt;&lt; <span class="hljs-string">" is: "</span> &lt;&lt; smallest &lt;&lt; <span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>The smaller number between 4 and 8 is: 4</p>
<h2 id="heading-the-swap-function">The <code>swap()</code> Function</h2>
<p>The <code>std::swap()</code> function lets you swap two values. It’s defined inside <code>&lt;algorithm&gt;</code> header file.</p>
<h3 id="heading-syntax-7"><strong>Syntax:</strong></h3>
<pre><code class="lang-plaintext">swap(a , b);
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><p><strong>a:</strong> First number</p>
</li>
<li><p><strong>b:</strong> Second number</p>
</li>
</ul>
<p><strong>Return Value:</strong> This function does not return any value.</p>
<h3 id="heading-example">Example:</h3>
<p>Here’s how it works:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">//  use of the swap() function</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;  // For the built-in swap() function</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;   </span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">int</span> firstNumber = <span class="hljs-number">8</span> ;
    <span class="hljs-keyword">int</span> secondNumber = <span class="hljs-number">9</span> ;


    <span class="hljs-comment">// Use the built-in swap() function to exchange values</span>
    swap(firstNumber, secondNumber);

    <span class="hljs-comment">// Display values after swapping</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"After the swap:"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; firstNumber &lt;&lt; <span class="hljs-string">" "</span> &lt;&lt; secondNumber &lt;&lt; <span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>After the swap:</p>
<p>9 8</p>
<h2 id="heading-the-tolower-function">The <code>tolower()</code> Function</h2>
<p>You can use the <code>tolower()</code> function to convert a given alphabet character to lowercase. It’s defined inside the <code>&lt;cctype&gt;</code> header.</p>
<h3 id="heading-syntax-8">Syntax:</h3>
<pre><code class="lang-plaintext">tolower (c);
</code></pre>
<p><strong>Parameter(s):</strong></p>
<ul>
<li><strong>c:</strong> The character to be converted.</li>
</ul>
<p><strong>Return Value:</strong></p>
<ul>
<li><p>Lowercase of the character c.</p>
</li>
<li><p>Returns c if c is not a letter.</p>
</li>
</ul>
<h3 id="heading-example-code-7">Example Code:</h3>
<p>Here’s how it works:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// C++ program</span>

<span class="hljs-comment">// use of tolower() function</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cctype&gt;     </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;   </span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Declare and initialize a string with uppercase characters</span>
    <span class="hljs-built_in">string</span> str = <span class="hljs-string">"FRECODECAMP"</span>;

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span>&amp; a : str) {
        a = <span class="hljs-built_in">tolower</span>(a);
    }

    <span class="hljs-comment">// Print the modified string </span>
    <span class="hljs-built_in">cout</span> &lt;&lt; str;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>freecodecamp</p>
<h2 id="heading-the-toupper-function">The <code>toupper()</code> Function</h2>
<p>You can use the <code>toupper()</code> function to convert the given alphabet character to uppercase. It’s defined inside the <code>&lt;cctype&gt;</code> header.</p>
<h3 id="heading-syntax-9">Syntax:</h3>
<pre><code class="lang-plaintext">toupper (c);
</code></pre>
<p><strong>Parameters:</strong></p>
<ul>
<li><strong>c:</strong> The character to be converted.</li>
</ul>
<p><strong>Return Value</strong></p>
<ul>
<li><p>Uppercase of the character c.</p>
</li>
<li><p>Returns c if c is not a letter.</p>
</li>
</ul>
<h3 id="heading-example-code-8">Example Code:</h3>
<p>Here’s how it works:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// use of toupper() function</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cctype&gt;     </span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;   </span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// Declare and initialize a string </span>
    <span class="hljs-built_in">string</span> str = <span class="hljs-string">"freecodecamp"</span>;

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span>&amp; a : str) {
        a = <span class="hljs-built_in">toupper</span>(a);
    }

    <span class="hljs-comment">// Output the converted uppercase string</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; str;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Output:</p>
<p>FREECODECAMP</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Inbuilt functions are helpful tools in competitive programming and in common programming tasks. These help in improving code readability and enhance the efficiency of code. In the above article, we discussed some very useful common inbuilt functions. Some common inbuilt functions are <code>max()</code>, <code>min()</code>, <code>sort()</code>, and <code>sqrt()</code>, etc. By using these inbuilt libraries, we can reduce boilerplate code and speed up the process of software development. These help in writing more concise, reliable, and maintainable C++ programs.</p>
<p>And if you'd like to support me and my work directly so I can keep creating these tutorials, <a target="_blank" href="https://paypal.me/ayushM010">you can do so here</a>. Thank you!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Improve Your C++ Skills by Coding an Audio Plugin ]]>
                </title>
                <description>
                    <![CDATA[ Do you want to build a practical project to help improve your C++ skills? Have you ever wanted to create your own unique audio effects? Then diving into C++ audio plugin development with the JUCE framework might be your next great step We just publis... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/improve-you-c-skills-by-coding-an-audio-plugin/</link>
                <guid isPermaLink="false">68190b8f1abafc5ea9d7efbf</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Mon, 05 May 2025 19:03:43 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1746547631263/2f0d40a4-1e84-4109-b102-1b99a3d7b96f.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Do you want to build a practical project to help improve your C++ skills? Have you ever wanted to create your own unique audio effects? Then diving into C++ audio plugin development with the JUCE framework might be your next great step</p>
<p>We just published a comprehensive tutorial on the freeCodeCamp.org YouTube channel that will help you improve you C++ skills by building an audio plugin. This course about writing code and gaining the skills to bring your sonic ideas to life.</p>
<p>Chuck from Matkat music created this course. He is a 3x Grammy nominated arranger, sax player, producer, and coder.</p>
<p>Here are just a few reasons why you should consider learning C++ audio plugin development with JUCE:</p>
<ul>
<li><p><strong>Unlock Creative Potential:</strong> Build custom effects and instruments that are perfectly tailored to your creative needs, going beyond the limitations of off-the-shelf plugins.</p>
</li>
<li><p><strong>Deepen Your Programming Skills:</strong> C++ is a powerful language widely used in the audio industry. Learning JUCE will enhance your C++ knowledge and introduce you to the intricacies of real-time audio programming.</p>
</li>
<li><p><strong>Tap into a Robust Framework:</strong> JUCE is a comprehensive open-source framework specifically designed for audio applications. It simplifies complex tasks and provides a solid foundation for building professional-grade plugins that run on multiple platforms.</p>
</li>
<li><p><strong>Understand Audio Processing:</strong> Gain a deep understanding of digital signal processing (DSP) concepts and how to implement them to create various audio effects like phaser, chorus, overdrive, and filters.</p>
</li>
<li><p><strong>Build Professional Tools:</strong> Develop the skills to create plugins with responsive graphical interfaces (GUIs), parameter controls, metering, and state management.</p>
</li>
</ul>
<p>Ready to take the plunge into the world of audio plugin development and create your own signature sound? Check out the full tutorial on <a target="_blank" href="https://www.youtube.com/watch?v=G4A5T3y5bJM">the freeCodeCamp.org YouTube channel</a> (8-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/G4A5T3y5bJM" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ C++ Setup and Installation Tools – CMake, vcpkg, Docker & Copilot ]]>
                </title>
                <description>
                    <![CDATA[ Setting up a C++ development environment can be one of the most challenging aspects for newcomers, especially when juggling different operating systems and toolchains. Whether you’re aiming to build robust applications or contribute to professional-g... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/c-setup-and-installation-tools-cmake-vcpkg-docker-and-copilot/</link>
                <guid isPermaLink="false">67f5418259aa448cc705cefd</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Tue, 08 Apr 2025 15:32:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1744126327420/6ec2b56c-d226-4fea-935c-ab78d6b83951.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Setting up a C++ development environment can be one of the most challenging aspects for newcomers, especially when juggling different operating systems and toolchains. Whether you’re aiming to build robust applications or contribute to professional-grade projects, having the right setup is essential for productivity and code quality. Modern C++ development is no longer just about writing code. It’s also about managing dependencies, automating builds, collaborating with version control, and even utilizing AI tools to accelerate development.</p>
<p>We just published a course on the <a target="_blank" href="http://freeCodeCamp.org">freeCodeCamp.org</a> YouTube channel that will teach you all about setting up a professional-grade C++ development environment using tools like CMake, vcpkg, Docker, and GitHub Copilot. This comprehensive course walks you through setting up your environment across Windows, Linux, and macOS, ensuring that you're well-equipped no matter what platform you're on. You’ll learn how to configure CMake and vcpkg, which simplifies the process of handling C++ libraries and dependencies. The course also covers Docker-based setups, making it easy to create portable, reproducible development environments. Daniel Gakwaya developed this course.</p>
<p>Let’s break down these essential tools:</p>
<p><strong>CMake</strong> is a widely used build system generator that helps manage the compilation process of C++ projects in a platform-independent manner. It allows you to write simple configuration files (CMakeLists.txt) to define how your code should be compiled, what dependencies to include, and how to organize your project. Instead of writing custom build scripts for each operating system, CMake lets you write one unified configuration and generate platform-specific build files automatically. This is a game-changer for cross-platform development and is favored by many open-source and enterprise-level projects.</p>
<p><strong>vcpkg</strong> is a C++ library manager developed by Microsoft that integrates seamlessly with CMake. It automates the process of downloading, building, and installing third-party libraries, saving you from the tedious and error-prone task of configuring each library manually. With a single command, you can install libraries like Boost, OpenCV, or fmt and have them ready to use in your project. vcpkg ensures consistency across systems and makes dependency management much more maintainable and scalable.</p>
<p><strong>Docker</strong> is a tool designed to create and manage lightweight containers that package your application and its environment. For C++ developers, Docker is especially useful for setting up reproducible development and build environments. You can configure a Docker container with all the necessary tools, compilers, and dependencies, and then share that container with teammates or deploy it in CI/CD pipelines. This approach eliminates the “it works on my machine” problem and is a staple in modern software development workflows.</p>
<p><strong>GitHub Copilot</strong>, powered by AI, acts as a virtual pair programmer that can assist you in writing code, suggesting functions, and even generating boilerplate based on your comments and existing code. In C++—a language known for its complexity and verbosity—Copilot can be a huge productivity booster. It helps by generating repetitive code structures, offering context-aware suggestions, and reducing the time spent searching for syntax or patterns. While it doesn't replace the need for solid C++ knowledge, it can accelerate development and reduce mental overhead.</p>
<p>This course also dives into using <strong>Git</strong> for version control—a fundamental skill in any programming career—and demonstrates how to use <strong>Compiler Explorer</strong>, a handy online tool for trying out C++ snippets and viewing the resulting assembly code in real time. It’s perfect for learning, testing, and understanding how your code is interpreted by the compiler.</p>
<p>Whether you're a beginner looking to set up your first project or a professional aiming to streamline your workflow, this course offers a practical, up-to-date guide to mastering the tools the pros use in C++ development. It's a great way to build a solid foundation and level up your C++ skills in today’s multi-platform, AI-augmented development landscape.</p>
<p>Watch the full course on <a target="_blank" href="https://youtu.be/0ffwhxW-uyw">the freeCodeCamp.org YouTube channel</a> (6-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/0ffwhxW-uyw" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An Animated Introduction to Programming in C++ ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, I’ll give you a comprehensive introduction to programming in C++. You don't need to have any previous programming experience in order to begin. Along the way, you will learn about the flow of control, variables, conditional statemen... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-programming-in-cpp/</link>
                <guid isPermaLink="false">67e48bff04e3150220f40379</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Beginner Developers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Mark Mahoney ]]>
                </dc:creator>
                <pubDate>Wed, 26 Mar 2025 23:21:35 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1743028744653/12f33ee5-4ef4-47da-b50d-060a9ee327ce.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, I’ll give you a comprehensive introduction to programming in C++. You don't need to have any previous programming experience in order to begin.</p>
<p>Along the way, you will learn about the flow of control, variables, conditional statements, loops, arrays, functions, structured data, pointers and dynamic memory, classes, common data structures, and working with databases.</p>
<p>Integrated Development Environments (IDE’s) are tools that allow you to write, run, and debug C++ programs. There are some great free C++ IDE’s out there.</p>
<p>If you own a Windows computer, I recommend using <a target="_blank" href="https://visualstudio.microsoft.com/vs/community">Visual Studio Community Edition</a>. If you own a Mac, I recommend using <a target="_blank" href="https://developer.apple.com/xcode">Xcode</a>. These provide robust features and excellent support for C++ development. If you're looking for a lightweight install on any platform, <a target="_blank" href="https://www.jetbrains.com/clion/download">CLion</a> is a fantastic choice.</p>
<p>For those who prefer not to install any software or are unable to, <a target="_blank" href="https://replit.com">replit</a> is a convenient web-based IDE that allows you to start coding immediately.</p>
<p>There are practice problems in each section so that you can use to practice while learning from the content. These are in the '<strong>Hands-On Practice</strong>' portion of each section. You will use your IDE to write and run these practice programs.</p>
<h2 id="heading-code-playbacks"><strong>Code Playbacks</strong></h2>
<p>This is not a traditional online tutorial or video series. Each section will have links to interactive ‘<strong>code playbacks’</strong> that visually animate the changes made to a program in a step-by-step manner.</p>
<p>A code playback shows how a program evolves by replaying all the steps in its development. It has an author-supplied narrative, screenshots, whiteboard-style drawings, and self-grading multiple choice questions to make the learning process more dynamic and interactive. Just click on the numbered comments on the left hand side of the screen to drive the playback forward.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1742956414812/64ed10ba-5f80-442b-b469-9d6462521578.png" alt="Screenshot showing what the playbacks look like" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Watch this short <a target="_blank" href="https://youtu.be/uYbHqCNjVDM">YouTube video</a> which explains how to view a code playback in more detail.</p>
<h2 id="heading-playback-press"><strong>Playback Press</strong></h2>
<p><a target="_blank" href="https://playbackpress.com/books">Playback Press</a> is a platform for sharing code playbacks. The site contains collections of code playbacks grouped together by language/technology into different ‘books’. If you want to see the full C++ book, you can go here: <a target="_blank" href="https://playbackpress.com/books/cppbook">An Animated Introduction to Programming in C++</a>.</p>
<p>Code playbacks on the platform include AI tutoring, mini-quizzes, and text-to-speech features.</p>
<p><a target="_blank" href="https://markm208.github.io/">Storyteller</a> is the free and open-source tool that powers code playbacks.</p>
<h2 id="heading-ai-tutor"><strong>AI Tutor</strong></h2>
<p>When viewing a code playback, you can ask an AI tutor about the code. It answers questions clearly and patiently, making it a helpful resource for learners. You can also ask the AI tutor to generate new self-grading multiple choice questions to test your knowledge of what you are learning.</p>
<p>In order to access the AI tutor and to generate new multiple choice questions, simply create a free account on Playback Press and add the <a target="_blank" href="https://playbackpress.com/books/cppbook">book</a> to your bookshelf. It is still free, but you do need to register in order to access the AI features.</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-part-1-variables">Part 1: Variables</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-part-2-selection">Part 2: Selection</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-part-3-looping">Part 3: Looping</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-part-4-arrays">Part 4: Arrays</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-part-5-functions">Part 5: Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-part-6-vectors">Part 6: Vectors</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-part-7-structured-data">Part 7: Structured Data</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-part-8-pointers">Part 8: Pointers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-part-9-object-oriented-programming">Part 9: Object-Oriented Programming</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-part-10-data-structures">Part 10: Data Structures</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-part-11-sqlite-databases">Part 11: SQLite Databases</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-comments-and-feedback">Comments and Feedback</a></p>
</li>
</ul>
<h3 id="heading-c-overview">C++ Overview</h3>
<p>C++ is a powerful, high-performance programming language that is widely used in various domains such as system development, game development, real-time simulations, and high-performance applications. It is an extension of the C programming language, adding object-oriented features, which makes it suitable for large-scale software engineering projects.</p>
<p>C++ provides fine-grained control over system resources and memory management, which can lead to highly optimized and efficient code. C++ remains a popular choice due to its versatility, performance, and the vast ecosystem of libraries and tools available.</p>
<h2 id="heading-part-1-variables"><strong>Part 1: Variables</strong></h2>
<p>Simply watching an experienced artist paint is not enough to say that you have learned how to become a painter. Watching an experienced artist is an important <em>part</em> of the learning process, but you can only call yourself a painter after struggling to make your own paintings first.</p>
<p>There are a lot of similarities between learning to paint and learning to program. The only way to truly learn programming is through practice!</p>
<p>So, let's get started. Follow along with the code playbacks below. Click the links below to load each code playback (it may help to open them in a new tab). Click on the playback comments on the left-hand side of the playback screen to step through the code's development.</p>
<h3 id="heading-flow-of-control"><strong>Flow of Control</strong></h3>
<p>The following playback explains the <strong>flow of control</strong> in a program by describing how to print to the screen from it:</p>
<ul>
<li><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/1/1">1.1 Name printer program</a></li>
</ul>
<h3 id="heading-variables-and-types"><strong>Variables and Types</strong></h3>
<p>This next group of programs describes declaring variables to hold data in a program. All variables have a <strong>type</strong> which specifies what can be stored in them and what operations can be performed on them.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/1/2">1.2 Distance formula</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/1/3">1.3 Basic types in C++</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/1/4">1.4 Number types</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/1/5">1.5 Characters and strings</a></p>
</li>
</ul>
<h3 id="heading-reading-from-the-keyboard"><strong>Reading from the Keyboard</strong></h3>
<p>This final group of programs builds on previous concepts and shows how to prompt the user for input.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/1/6">1.6 Weekly pay calculator</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/1/7">1.7 Distance formula revisited</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/1/8">1.8 Gas Mileage</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice"><strong>Hands-On Practice</strong></h3>
<p>Now that you have reviewed the guided code walk-throughs, write a program that prompts the user for three integers: one representing an hour, one representing a minute, and one representing a second. Next, calculate the number of seconds until midnight based on the time that was input. Print the number of seconds until midnight on the screen.</p>
<p>Then, prompt the user for a single integer representing the number of seconds until midnight. From that value, do the reverse calculation to find the hour, minute, and second of that time. Print it to the screen in a time format HH:MM:SS.</p>
<h2 id="heading-part-2-selection"><strong>Part 2: Selection</strong></h2>
<p>This section discusses altering the flow of control with <code>if/else</code> statements. These statements ask the computer to evaluate whether a condition is <code>true</code> or <code>false</code> and changes the flow of control based on the answer. It also explains the data type, <code>bool</code>, which can hold either true or false and it shows a few examples of how to use selection with <code>if</code>, <code>if/else</code>, <code>if/else if/else</code>, and <code>switch</code> statements.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/2/1">2.1 Booleans</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/2/2">2.2 Even/odd calculator</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/2/3">2.3 Overtime pay with an if/else</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/2/4">2.4 Water temperature</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/2/5">2.5 Switch</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-1"><strong>Hands-On Practice</strong></h3>
<p>Now that you have reviewed the guided code walk-throughs, try to write a few programs:</p>
<h4 id="heading-problem-1"><strong>Problem 1</strong></h4>
<p>Problem 1 asks you to write a program to determine if one date comes after another. The program will ask for two sets of dates. Next, the program will determine if the first date comes before, is equal to, or comes after.</p>
<pre><code class="lang-plaintext">Enter in the first month: 2
Enter in the first day: 21
Enter in the first year: 2012

Enter in the second month: 2
Enter in the second day: 22
Enter in the second year: 2011

The first date comes after the second.
</code></pre>
<h4 id="heading-problem-2"><strong>Problem 2</strong></h4>
<p>Problem 2 asks you to write a program that prompts the user for a date and determines if that date is valid. For example, 9/19/2017 is a valid date, but these are not valid dates:</p>
<ul>
<li><p>4/31/2006 (only 30 days in April)</p>
</li>
<li><p>2/29/2005 (not a leap year)</p>
</li>
<li><p>16/1/2010 (invalid month)</p>
</li>
<li><p>4/59/2013 (invalid day)</p>
</li>
</ul>
<p>If the date is correct, print it out. If it is incorrect, display an error message explaining why the date is not correct.</p>
<h4 id="heading-problem-3"><strong>Problem 3</strong></h4>
<p>Problem 3 asks you to write a program that will calculate change for a sales purchase. Your program should prompt for a sales price. Validate that the data entered is a number greater than 0. If the data entered is incorrect, display an error message and end the program.</p>
<p>Next, prompt the user for the amount that the customer will pay to the cashier. Validate that this value is greater than or equal to the sales price. If it is not, display an error message and end the program.</p>
<p>If the entry is correct, your program must calculate the amount of change to return to the user. Next, calculate what bills and coins that the the cashier needs to return to the customer. The fewest number of paper bills and coins should be returned. You can make change in many different combinations, but the only correct implementation is the one that returns the fewest paper bills and coins.</p>
<p>Display the number of each of the bills and coins. Here is a sample run of the program:</p>
<pre><code class="lang-plaintext">Enter in a sales amount: $20.38
Enter in the amount the customer pays: $30.00

The change due back is $9.62

You should give the customer this change:
0 $100 bills
0 $50 bills
0 $20 bills
0 $10 bills
1 $5 bills
4 $1 bills
1 Half Dollars
0 Quarters
1 Dimes
0 Nickels
2 Pennies
</code></pre>
<p>Because of the way arithmetic works with float variables, storing the monetary values as floats may cause some problems.</p>
<p>For example, if you had a float variable that held 1.29 to represent $1.29 and you subtracted the .05 from it (to represent giving back a nickel), you would think that you would be left with exactly 1.24. Unfortunately, the computer might store that value or it might store 1.2399999 or 1.2400001 instead of exactly 1.24.</p>
<p>These very small inconsistencies can cause a problem calculating the number of pennies to return. Consider converting the amounts into ints to solve this problem.</p>
<h2 id="heading-part-3-looping"><strong>Part 3: Looping</strong></h2>
<p>This group of playbacks discusses repeatedly executing the same code over and over again in a loop. They show how to create count controlled and event controlled loops with the <code>while</code> keyword, nested loops, a <code>for</code> loop, and how to exit a loop with <code>break</code> and <code>continue</code>.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/3/1">3.1 A simple loop</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/3/2">3.2 More loops</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/3/3">3.3 Summation</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/3/4">3.4 Nested loop</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/3/5">3.5 <code>for</code> loop</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/3/6">3.6 Capitalization</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/3/7">3.7 <code>break</code> and <code>continue</code></a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-2"><strong>Hands-On Practice</strong></h3>
<p>Now that you have reviewed the guided code walk-throughs, write a few programs:</p>
<h4 id="heading-problem-1-1"><strong>Problem 1</strong></h4>
<p>Problem 1 asks you to write a program that will calculate the sum of the squares from 1 up to and including that number. For example, if the user entered in the value 5, then the sum of the squares for the numbers one through five would be (1 + 4 + 9 + 16 + 25) = 55.</p>
<p>Your program should repeatedly calculate this value until the user enters in a value of -99. This is the sentinel value that the program uses to determine when to quit.</p>
<pre><code class="lang-plaintext">Enter in an integer number(ex. 10), -99 to quit: 5
The sum of the squares up to 5 is 55

Enter in an integer number(ex. 10), -99 to quit: 4
The sum of the squares up to 4 is 30

Enter in an integer number(ex. 10), -99 to quit: -99
Have a nice day!
</code></pre>
<h4 id="heading-problem-2-1"><strong>Problem 2</strong></h4>
<p>Problem 2 asks you to write a program that will determine whether a number is prime or not. A prime number is any number that is evenly divisible only by the number one and itself.</p>
<p>7 is prime because the only numbers that divide into it without a remainder are 1 and 7.</p>
<p>12 is not prime because the numbers that divide into it evenly are 1, 2, 3, 4, 6, and 12.</p>
<p>Your program will prompt for a number and then display whether the number is prime or not. The number entered must be a positive number. Repeatedly prompt for a number until a positive number is entered.</p>
<h4 id="heading-problem-3-1"><strong>Problem 3</strong></h4>
<p>Problem 3 asks you to calculate a mortgage schedule for someone thinking of buying a new house. The inputs to determine a monthly schedule are the principal loan amount and the annual interest rate. Assume this will be a conventional 30 year loan.</p>
<p>Your program should prompt for these inputs and find a monthly payment using this calculation:</p>
<pre><code class="lang-plaintext">                                   monthly interest rate                                              
monthly payment =  ------------------------------------------------- * principal
                   1 - (1 + monthly interest rate)^-number of months
</code></pre>
<p>Notice that you will have to calculate the monthly interest rate (the annual interest rate divided by 12.0) and number of months (360 for a 30 year loan). The ^ in this formula means raise one number to a power. There is a function called <code>pow()</code> which raises one number to another and returns the result. For example, if you wanted to raise 2 to the -3rd power, you would do this:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">float</span> result = <span class="hljs-built_in">pow</span>(<span class="hljs-number">2.0</span>, <span class="hljs-number">-3.0</span>);
</code></pre>
<p>After you have calculated the monthly payment, create a summary of the loan characteristics. Display the loan amount, the interest rate, the monthly payment, the total amount paid for the loan, the total amount of interest paid, and the ratio of amount paid over the principal.</p>
<p>After you have printed the summary, you can begin to make the schedule. Prompt the user for the ending month to display in the schedule. The schedule should display the month number, the monthly payment, the amount paid in principal in that month, the amount paid in interest in that month, and the amount remaining in the principal (the amount paid in principle each month is deducted from the remaining principle). A month's interest amount is equal to monthly interest rate times the remaining principal. The monthly principal is the difference between the monthly payment and the monthly interest paid. Remember to update the remaining principal after every month.</p>
<p>After each year of the schedule has been printed, display a message with the year number.</p>
<h2 id="heading-part-4-arrays"><strong>Part 4: Arrays</strong></h2>
<p>This batch of programs shows how to use arrays in C/C++. An array is a collection of variables (all of the same type) that have a single name and sit next to each other in memory. Loops are almost always used to go through the elements of an array. They show how to create two and three dimensional arrays and use the random number generator in C/C++.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/4/1">4.1 Arrays</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/4/2">4.2 Average and standard deviation of an array of values</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/4/3">4.3 Problems with arrays</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/4/4">4.4 Flipping coins</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/4/5">4.5 Multi-dimensional arrays</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-3"><strong>Hands-On Practice</strong></h3>
<p>Now that you have reviewed the guided code walk-throughs, write a few programs:</p>
<h4 id="heading-problem-1-2"><strong>Problem 1</strong></h4>
<p>Problem 1 asks you to write a program that displays a menu with three options.</p>
<p>The first option allows the user to enter in a month number (between 1-12) and a day number within that month (1-31) and calculates the day number in the year. January 1 is day 1. January 31 is day 31. February 1 is day 32. February 28 is day 59. December 31 is day 365 (don’t worry about leap years). If the user enters an invalid combination (like February 31) the program should continuously prompt the user to enter in a new value until they enter a valid date.</p>
<p>The second menu option allows the user to enter in a day number (1-365) and prints out the month name and day number of that month. If the user enters in 59, the program should print out:</p>
<pre><code class="lang-plaintext">Day 59 is February 28
</code></pre>
<p>If the user enters an invalid day number, the program should continuously prompt the user to enter in a new value until it is in the correct range.</p>
<p>The last menu option allows the user to quit the program. The menu should repeatedly be displayed until the user chooses to quit the program.</p>
<p>Use an array of integers to hold the number of days in each of the months. Use the array to keep a running sum to help with your day calculations. You may also want to create an array of strings with the month names.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> numDaysInMonths[] = {<span class="hljs-number">31</span>, <span class="hljs-number">28</span>, <span class="hljs-number">31</span>, <span class="hljs-number">30</span>, <span class="hljs-number">31</span>, <span class="hljs-number">30</span>, <span class="hljs-number">31</span>, <span class="hljs-number">31</span>, <span class="hljs-number">30</span>, <span class="hljs-number">31</span>, <span class="hljs-number">30</span>, <span class="hljs-number">31</span>};
</code></pre>
<p>Here is a sample run of the program:</p>
<pre><code class="lang-plaintext">1. Enter in a month and day
2. Enter in a day number
3. Quit
Enter in a menu option: 1

Enter in a month number: 2
Enter in a day number: 1

February 1 is day 32

1. Enter in a month and day
2. Enter in a day number
3. Quit
Enter in a menu option: 2

Enter in a day number: 59
Day 59 is February 28

1. Enter in a month and day
2. Enter in a day number
3. Quit
Enter in a menu option: 3
</code></pre>
<h4 id="heading-problem-2-2"><strong>Problem 2</strong></h4>
<p>Problem 2 asks you to create a program that will find the number of days in between two dates.</p>
<p>For example, say a user would like to know how many days are in between two dates (1/1/2000) and (3/19/2030). The program must find out how many whole days are in between these two dates (include the starting and ending date).</p>
<p>If the two dates are in the same year, then the algorithm to find the number of days may be different than if the dates are in different years. Your program must handle each case.</p>
<p>Here is a sample run of the program:</p>
<pre><code class="lang-plaintext">Enter in a start month: 1
Enter in a start day: 1
Enter in a start year: 2000

Enter in an end month: 3
Enter in an end day: 19
Enter in an end year: 2030

There are 11035 days in between 1/1/2000 and 3/19/2030
</code></pre>
<h2 id="heading-part-5-functions"><strong>Part 5: Functions</strong></h2>
<p>This group of playbacks describes another flow of control-altering mechanism called functions. A function is a named block of code that can be <em>called</em> and the flow of control will jump to it.</p>
<p>When calling a function, some data can be passed into it (called parameters) and the function can return a piece of data when it is complete (called a return value). These playbacks discuss passing in data 'by value' versus 'by reference'. They show that every variable has a limited lifetime that it sits in memory, or scope.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/5/1">5.1 Functions</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/5/2">5.2 Value returning functions</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/5/3">5.3 Functions with parameters</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/5/4">5.4 Passing parameters by reference</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/5/5">5.5 The scope of variables</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/5/6">5.6 Prime number function</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/5/7">5.7 Passing arrays to functions</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-4"><strong>Hands-On Practice</strong></h3>
<p>Now that you have reviewed the guided code walk-throughs, write a few programs:</p>
<h4 id="heading-problem-1-3"><strong>Problem 1</strong></h4>
<p>Problem 1 asks you to extend the prime number problem from a previous section. Write a program that includes a function that will print all the prime numbers in a range. The program will ask for a lower bound and an upper bound and print all the primes in that range.</p>
<h4 id="heading-problem-2-3"><strong>Problem 2</strong></h4>
<p>Problem 2 asks you to write a function that takes an integer year number and returns a <code>bool</code> whether that year is a leap year or not. The calculation for leap year is as follows:</p>
<ul>
<li><p>most years evenly divisible by four are leap years</p>
</li>
<li><p>if a year is divisible by four and is a century year, like 1800 or 1900, then it is NOT a leap year</p>
</li>
<li><p>if a century year also happens to be divisible by 400, like 2000 or 2400, then it is a leap year</p>
</li>
</ul>
<p>The function should look something like this:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">isLeapYear</span><span class="hljs-params">(<span class="hljs-keyword">int</span> year)</span>
</span>{
    <span class="hljs-comment">//calculate if it is leap year or not and return true or false</span>
}
</code></pre>
<h4 id="heading-problem-3-2"><strong>Problem 3</strong></h4>
<p>Problem 3 asks you to write a program that will print a calendar for a whole year given the day that January 1st falls on. Your program will prompt for the day that January 1st falls on and the year. You must print the calendar for all 12 months of that year. The options for the first day of the year will be entered with the first three letters of each of the seven days of the week from Sunday ('sun') to Saturday ('sat').</p>
<p>The year does not need to be validated, but the day of the week does. You should not allow the user to enter in a value other than 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', or 'sat'.</p>
<p>The format of your calendar should be very similar to the example below. You must use at least one function in addition to the main function. Pass data between functions, do not use global variables.</p>
<p>The final requirement is that your program should only display one month at a time and then wait for some user input before continuing.</p>
<p>It is very important that you come up with a plan to solve this program before you begin coding (as it is with every program). Think about how you would print a single month's calendar given the day of the month that it begins on.</p>
<p>Sample Output:</p>
<pre><code class="lang-plaintext">What year do you want the calendar for?
2003

What day of the week does January 1st fall on (sun for Sunday, mon for Monday, etc..)?
s
Invalid Entry - please enter the first three letters of the day

What day of the week does January 1st fall on (sun for Sunday, mon for Monday, etc..)?
wed

    January 2003
 S  M  T  W  T  F  S
---------------------
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Do you want to continue? y

   February 2003
 S  M  T  W  T  F  S
---------------------
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28

Do you want to continue? y
...
...
</code></pre>
<h2 id="heading-part-6-vectors"><strong>Part 6: Vectors</strong></h2>
<p>C++ comes with the Standard Template Library (STL) which is a collection of different containers. This section will cover vectors. A <code>vector</code> is an array-based container that holds data very much like an array does but it is <em>smarter</em>. It knows how many elements are in it and it can grow as the program is running. It also shows how to read and write data from a file, efficiently search through an array-based container, sort values, and more.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/6/1">6.1 <code>vector</code></a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/6/2">6.2 Passing a <code>vector</code> to a function</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/6/3">6.3 Advanced features of <code>vector</code>s</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/6/4">6.4 Reading from a file and storing in a <code>vector</code></a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/6/5">6.5 Linear search and binary search</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/6/6">6.6 Bubble sort</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/6/7">6.7 Writing to a file</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/6/8">6.8 Two dimensional <code>vector</code>s</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-5"><strong>Hands-On Practice</strong></h3>
<p>Now that you have reviewed the guided code walk-throughs, write a program to read in whole words from a file and store them in a vector of strings. Create a simple text file (.txt) using your coding editor. Then add a few sentences of text to it. Strip any punctuation marks from the words and make them all lowercase letters. Only store a word in the vector if it is not already present.</p>
<h2 id="heading-part-7-structured-data"><strong>Part 7: Structured Data</strong></h2>
<p>This section describes how to use structured data types. Structured data types allow you to group related data together so that it can be passed around easily.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/7/1">7.1 Simple <code>struct</code></a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/7/2">7.2 Hierarchical <code>struct</code>s</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/7/3">7.3 <code>vector</code>s as members of <code>struct</code>s</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/7/4">7.4 <code>struct</code>s with a <code>vector</code> of objects</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/7/5">7.5 Calculus with <code>struct</code>s</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-6"><strong>Hands-On Practice</strong></h3>
<p>Now that you have reviewed the guided code walk-throughs, write a program that has a struct to represent a cell phone. Every cell phone has a model name and manufacturer along with a camera with a mega-pixel resolution. For example, a user may want to store information about an Apple IPhone X with a 12 MP camera or a Google Pixel 4 with a 16 MP camera.</p>
<p>Your program will create three cell phone objects, fill them, and then add them to a vector. Lastly, print out the information about each cell phone on the screen.</p>
<p>Write a function that takes a cell phone object by reference and prompts the user to enter in the model, manufacturer, and camera resolution. Write another function that prints information about a cell phone. Write a function that takes a vector of cell phones and prints each one.</p>
<h2 id="heading-part-8-pointers"><strong>Part 8: Pointers</strong></h2>
<p>This section describes pointers in C/C++. A pointer is a variable that holds the address of another variable. Pointers are important because they allow us to use a special section of memory called the 'heap'. This section discusses the different types of memory that can be used in a program (global, local, and dynamic).</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/8/1">8.1 Simple pointers</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/8/2">8.2 Pointer to an object</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/8/3">8.3 Vectors of pointers</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/8/4">8.4 Arrays are pointers</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/8/5">8.5 Passing data to functions with pointers</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/8/6">8.6 Comparing pointers</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/8/7">8.7 Three types of variables- global, local, and dynamic</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/8/8">8.8 Dynamic variables example</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/8/9">8.9 Dangling pointers and null pointers</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/8/10">8.10 Dynamic array of students</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-7"><strong>Hands-On Practice</strong></h3>
<p>Now that you have reviewed the guided code walk-throughs, write a program that will read a sequence of words from the keyboard and store them in a dynamic array of strings. Use the word 'quit' as the word that terminates the input. Print the words back to the screen in the order in which they were entered, each on its own line. Do not store the same word twice.</p>
<p>Up until now, the size of an array has been determined at compile time. Now that you know about pointers and about the keyword <code>new</code>, write a program which is not restricted to selecting an upper bound at compile time for the number of words which can be read in.</p>
<p>One way to do this is to use <code>new</code> to create arrays of strings on the fly. Each time an array fills up, dynamically create an array which is twice as large, copy over the contents of the existing array to the new array, and continue (remember to <code>delete</code> the original array). Start with an array of 5 elements.</p>
<p>Here is an example of the output:</p>
<pre><code class="lang-plaintext">Enter in some text and end with the word quit:
This lab asks you to write a program that will read a sequence of words from the keyboard and store them in a dynamic array of strings. Use the word 'quit' as the word that terminates the input. Print the words back to the screen in the order in which they were entered each on its own line. Do not store the same word twice. quit

Doubling Array from 5 to 10
Doubling Array from 10 to 20
Doubling Array from 20 to 40
Doubling Array from 40 to 80
1. This
2. lab
3. asks
4. you
5. to
6. write
7. a
8. program
9. that
10. will
11. read
12. sequence
13. of
14. words
15. from
16. the
17. keyboard
18. and
19. store
20. them
21. in
22. dynamic
23. array
24. strings.
25. Use
26. word
27. 'quit'
28. as
29. terminates
30. input.
31. Print
32. back
33. screen
34. order
35. which
36. they
37. were
38. entered
39. each
40. on
41. its
42. own
43. line.
44. Do
45. not
46. same
47. twice.
Press any key to continue . . .
</code></pre>
<h2 id="heading-part-9-object-oriented-programming"><strong>Part 9: Object-Oriented Programming</strong></h2>
<p>This section discusses object-oriented programming using classes in C++. A class is like a <code>struct</code>, except that in addition to collecting data, it also collects methods that work on that data. This is called encapsulation. It also discusses inheritance and polymorphism that make it easier to reuse code.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/9/1">9.1 Simple class</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/9/2">9.2 A class with data members</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/9/3">9.3 A class with objects for data members</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/9/4">9.4 Common word analysis</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/9/5">9.5 Student and course registration system</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/9/6">9.6 Inheritance and polymorphism</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/9/7">9.7 Shape inheritance hierarchy</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/9/8">9.8 Inheritance and polymorphism in C++</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/9/9">9.9 Copy Constructor Example</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-8"><strong>Hands-On Practice</strong></h3>
<p>Now that you have reviewed the guided code walk-throughs, write a few programs:</p>
<h4 id="heading-problem-1-4"><strong>Problem 1</strong></h4>
<p>Problem 1 asks you to create a Date class to represent a date.</p>
<p>There should be an int for the day number, month number, and year number declared in the private section. Instead of having a setter for each of those, have one method called setDate(int m, int d, int y) that sets the date. You can have a getter method for each piece of data.</p>
<p>Add two constructors: one that takes no data and sets the date to 1/1/2000, and another that takes three ints to set the date.</p>
<p>Include a print() method that will print the date in this format: MM/DD/YYYY and a method called printLong() that prints in this format: <code>MonthName Day, Year</code>. For example, the first day of the 21st century should print <code>January 1, 2000</code>.</p>
<p>Include a method to add some number of days, months, and years to a Date:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">addDays</span><span class="hljs-params">(<span class="hljs-keyword">int</span> d)</span>
<span class="hljs-keyword">void</span> <span class="hljs-title">addMonths</span><span class="hljs-params">(<span class="hljs-keyword">int</span> m)</span>
<span class="hljs-keyword">void</span> <span class="hljs-title">addYears</span><span class="hljs-params">(<span class="hljs-keyword">int</span> y)</span></span>
</code></pre>
<h4 id="heading-problem-2-4"><strong>Problem 2</strong></h4>
<p>Problem 2 asks you to create some related classes for playing card games. The data needed to be stored for a card is a numeric value and a suit. A card is responsible for being able to display itself. For example, when we want to display a two of hearts, ten of diamonds, jack of clubs, or ace of spades, the output would look like this:</p>
<pre><code class="lang-plaintext">2 of Hearts
10 of Diamonds
J of Clubs
A of Spades
</code></pre>
<p>Next, create a deck class. A deck is a collection of fifty-two cards. Each card is unique. There should be a card with a numeric value from two to the ace in each of the four suits. The responsibilities of the deck class are that it must be able to shuffle itself and deal out some number of cards from the deck. To shuffle the deck, you will need to randomly move cards around in the deck. You can generate a random number in C++ using the rand() function.</p>
<p>When dealing out cards, the user will ask the deck for some number of cards. If there are enough cards in the deck, it should deal those cards out. Once a card is dealt from the deck, it cannot be dealt again from the same deck. The user will pass in a vector of cards and the deck will fill it with the number of cards requested. If there aren't enough cards in the deck, print an error message and then kill the program with an exit(0).</p>
<p>When creating a class, you always have to think about the data needed for the class and the responsibilities of the class. The data for the class should be private and an interface to the class should be provided.</p>
<p>Think about how each card and deck should be constructed. Write at least one constructor for each class. Write the card class first and test it in a driver program. Then work on the deck class.</p>
<p>To test the deck, create a deck object, ask for 52 cards, and print each of those cards to the screen.</p>
<p>Next, alter the program so that it will allow a person to evaluate the probabilities of getting certain poker hands. Poker is a card game played with a deck of 52 cards. In this program, you only need to handle the five card variety of poker. The program will repeatedly get groups of five cards from the deck and count how many times each hand occurs.</p>
<p>In most variations of poker, the precedence of hands goes like this:</p>
<pre><code class="lang-plaintext">Royal Flush - 5 cards that are a straight (5 cards in numeric order) and a flush (5 cards that are the same suit) from the 10 to the Ace.
Straight Flush - 5 cards that are a straight (5 cards in numeric order) and a flush (5 cards that are the same suit).
Four of a Kind - any 4 cards with the same number.
Full House - three of a kind (3 cards with the same number) and a pair (two cards with the same number).
Flush - any 5 cards of the same suit.
Straight - any 5 cards in numeric order.
Three of a Kind - any 3 cards with the same number.
Two Pair - 2 sets of pairs.
Pair - any 2 cards with the same number.
High Card in your Hand - if you don't have any of the above, your high card is the best hand.
</code></pre>
<p>You will need to create additional classes with more responsibilities than the Deck and Card classes.</p>
<p>Your program needs an 'evaluator' that can look at a collection of cards and determine the best hand that can be made from those cards. In order to determine probabilities, deal a great number of hands and keep track of how many times each hand shows up.</p>
<p>In other words, your program might create 100,000 collections of five cards to be evaluated. The evaluator will count how many times a royal flush comes up, how many times a straight flush comes up, an so on. Your program will show the probabilities as percentages of the likelihood of getting each hand.</p>
<p>Below is a driver to illustrate how to use the evaluator:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">//five card evaluator</span>
    <span class="hljs-comment">//create a poker evaluator for 5 card poker</span>
    PokerEvaluator fiveCardPokerEvaluator;

    <span class="hljs-comment">//set the number of hands to play - one hundred thousand this time</span>
    fiveCardPokerEvaluator.setNumberOfHandsToPlay(<span class="hljs-number">100000</span>);

    <span class="hljs-comment">//play all the hands and track the statistics, then print the results to the screen</span>
    fiveCardPokerEvaluator.playAndDisplay();

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<h2 id="heading-part-10-data-structures"><strong>Part 10: Data Structures</strong></h2>
<p>This section describes how to build some common data structures: a hash table, a binary search tree, and a graph. It also describes how to use the STL <code>unordered_map</code> class.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/10/1">10.1 Simple linked list</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/10/2">10.2 Simple hash table</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/10/3">10.3 More complex hash table</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/10/4">10.4 STL <code>unordered_map</code></a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/10/5">10.5 Binary search tree</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/10/6">10.6 Graph adjacency matrix</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-9"><strong>Hands-On Practice</strong></h3>
<p>Now that you have reviewed the guided code walk-throughs, write a program that includes a class which is equivalent of the <code>vector</code> called SafeArray. SafeArray has a method called <code>at</code> that returns the element at the specified position.</p>
<p>A SafeArray maintains a pointer to an array on the heap. Use the pointer to make the array grow and shrink with calls to <code>push_back</code> and <code>pop_back</code>.</p>
<p>The SafeArray will have a method called <code>size</code> that returns the number of items in it. Include a default constructor that sets the initial size of the underlying array to hold 10 elements. Include a destructor to <code>delete</code> the array when the SafeArray falls out of scope.</p>
<h2 id="heading-part-11-sqlite-databases"><strong>Part 11: SQLite Databases</strong></h2>
<p>This section describes working with a SQLite database. SQLite is my favorite Database Management System (DBMS), because it is powerful and easy to add to any program. This section assumes that you are familiar with relational database design and SQL.</p>
<p>The first program shows how to use the API to write and run SQL queries in a C++ program. In the second, some of the repetitive code is abstracted into a separate class. In the third, transactions in SQLite are explained and it shows that they can be used to ensure the ACID properties of a database:</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/11/1">11.1 The C++ SQLite API</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/11/2">11.2 An Object Oriented Auction Program</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/chapter/11/3">11.3 SQLite Transactions</a></p>
</li>
</ul>
<h3 id="heading-hands-on-practice-10"><strong>Hands-On Practice</strong></h3>
<p>Extend the auction program from the second playback to include a method that prints the names and email addresses of all of the users who won an auction. Then write a method that prints an item followed by the names and email addresses of anyone who made a bid on the item.</p>
<h2 id="heading-comments-and-feedback"><strong>Comments and Feedback</strong></h2>
<p>You can find all of these code playbacks in my free book, <a target="_blank" href="https://playbackpress.com/books/cppbook/">An Animated Introduction to Programming in C++</a>. There are more free books here:</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/pybook">An Animated Introduction to Programming with Python</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlbook">Database Design and SQL for Beginners</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/workedsqlbook">Worked SQL Examples</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook">Programming with SQLite</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/webdevbook">An Introduction to Web Development from Back to Front</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook">An Animated Introduction to Clojure</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook">An Animated Introduction to Elixir</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/rubybook">A Brief Introduction to Ruby</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/flutterbook">Mobile App Development with Dart and Flutter</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/patternsbook">OO Design Patterns with Java</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/wordzearchbook">How I Built It: Word Zearch</a></p>
</li>
</ul>
<p>Comments and feedback are welcome via email: <a target="_blank" href="mailto:mark@playbackpress.com">mark@playbackpress.com</a>.</p>
<p>If you'd like to support my work and help keep Playback Press free for all, consider donating using <a target="_blank" href="https://github.com/sponsors/markm208">GitHub Sponsors</a>. I use all of the donations for hosting costs. Your support helps me continue creating educational content like this. Thank you!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
