<?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>Sun, 24 May 2026 11:07:28 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/c-2/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Run SQL-Like Queries on C/C++ Files ]]>
                </title>
                <description>
                    <![CDATA[ Hello everyone! I'm a Software engineer who's interested in low-level programming, compilers, and tool development. At the end of 2023, I published my first article on freeCodeCamp about how I created a SQL-like Language to run queries on local Git r... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/run-sql-like-queries-on-cplusplus-files/</link>
                <guid isPermaLink="false">66d45d9ba44b8bb91150f657</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Amr Hesham ]]>
                </dc:creator>
                <pubDate>Thu, 02 May 2024 19:35:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/gitql_banner-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hello everyone! I'm a Software engineer who's interested in low-level programming, compilers, and tool development.</p>
<p>At the end of 2023, I published my first article on freeCodeCamp about how <a target="_blank" href="https://www.freecodecamp.org/news/gql-design-and-implementation/">I created a SQL-like Language to run queries on local Git repositories</a>. If you want a bit more context, give it a read.</p>
<p>At the start of 2024, the project got bigger and bigger with more features and amazing contributors, and I started to think: what if I could run SQL-like queries not only on .git files but on any kind of local and remote data?</p>
<p>In my last article about <a target="_blank" href="https://www.freecodecamp.org/news/how-to-run-sql-like-queries-on-files/">How to Run SQL-Like Queries on Files</a>, I explained the internal design of the GitQL SDK components and how to use it with any kind of data in general and how to implement the FileQL project.</p>
<p>In this article, I will explain how I used the GitQL SDK to implement the ClangQL (Clang Query Language) project, which is a tool that helps you run SQL-like queries on local C/C++ files.</p>
<h2 id="heading-how-i-came-up-with-the-clangql-project">How I Came Up with the ClangQL Project</h2>
<p>As I mentioned in my past articles, GitQL SDK can run SQL-like queries on any local or remote structured data. Also, the compiler parses your code into an AST (Abstract Syntax Tree) Data structure. So the question that jumped into my mind was, why not run the query on the Abstract Syntax Tree?</p>
<p>There were no limitations I could think of for implementing this idea, so I started to think of the two main requirements for using GitQL: creating the Data Schema to describe the table structures and columns types, and implementing the Data Provider component to provide the data which in our case is the ATS information and mapping it to the Engine format.</p>
<h3 id="heading-the-data-schema-for-the-cc-code">The Data Schema for the C/C++ Code</h3>
<p>You can think of the Data Schema as the place where we put structure and relationships of our data – for example, which tables we have, and for each table what columns they contain, and finally the types of each column.</p>
<p>This information is very useful when you're performing type checking and detecting if the user has written the wrong column name, for example, which is not defined in the selected table they want to use.</p>
<p>In our case, the tables can be classes, structs, enumerations, functions, variables and any other data that can be read from C++ such as macros and so on. But I decided to start simple with functions and variables only, then I planned to add other kinds.</p>
<p>So for the functions table, let's define what columns we need to include. The columns and types are not hard to guess, so let's take a normal function as an example. It has the name <code>Text</code>, and it returns type as <code>Text</code>, the number of parameters as <code>Int</code>, other C++ flags as Booleans (for example, is it a virtual function <code>is_virtual</code> or a pure virtual function <code>is_pure_virtual</code>?), and another flag to tell you if it is a static function <code>is_static</code>.</p>
<p>So to create a Data Schema you need to define two things: what tables you have, and what columns there are in this table. For example, in the functions table it will look like this:</p>
<pre><code class="lang-rust">lazy_static! {
    <span class="hljs-keyword">pub</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">ref</span> TABLES_FIELDS_NAMES: HashMap&lt;&amp;<span class="hljs-symbol">'static</span> <span class="hljs-built_in">str</span>, <span class="hljs-built_in">Vec</span>&lt;&amp;<span class="hljs-symbol">'static</span> <span class="hljs-built_in">str</span>&gt;&gt; = {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> map = HashMap::new();
        map.insert(
            <span class="hljs-string">"functions"</span>,
            <span class="hljs-built_in">vec!</span>[
                <span class="hljs-string">"name"</span>,
                <span class="hljs-string">"signature"</span>,
                <span class="hljs-string">"args_count"</span>,
                <span class="hljs-string">"return_type"</span>,
                <span class="hljs-string">"class_name"</span>,
                <span class="hljs-string">"is_method"</span>,
                <span class="hljs-string">"is_virtual"</span>,
                <span class="hljs-string">"is_pure_virtual"</span>,
                <span class="hljs-string">"is_static"</span>,
                <span class="hljs-string">"is_const"</span>,
                <span class="hljs-string">"has_template"</span>,
                <span class="hljs-string">"access_modifier"</span>,
                <span class="hljs-string">"is_variadic"</span>,
                <span class="hljs-string">"file"</span>,
                <span class="hljs-string">"line"</span>,
                <span class="hljs-string">"column"</span>,
                <span class="hljs-string">"offset"</span>,
            ],
        );
    }
}
</code></pre>
<p>You also need to define the expected data type for each column:</p>
<pre><code class="lang-rust">lazy_static! {
    <span class="hljs-keyword">pub</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">ref</span> TABLES_FIELDS_TYPES: HashMap&lt;&amp;<span class="hljs-symbol">'static</span> <span class="hljs-built_in">str</span>, DataType&gt; = {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> map = HashMap::new();
        map.insert(<span class="hljs-string">"name"</span>, DataType::Text);
        map.insert(<span class="hljs-string">"type"</span>, DataType::Text);
        map.insert(<span class="hljs-string">"signature"</span>, DataType::Text);
        map.insert(<span class="hljs-string">"args_count"</span>, DataType::Integer);
        map.insert(<span class="hljs-string">"return_type"</span>, DataType::Text);
        map.insert(<span class="hljs-string">"class_name"</span>, DataType::Text);
        map.insert(<span class="hljs-string">"is_method"</span>, DataType::Boolean);
        map.insert(<span class="hljs-string">"is_virtual"</span>, DataType::Boolean);
        map.insert(<span class="hljs-string">"is_pure_virtual"</span>, DataType::Boolean);
        map.insert(<span class="hljs-string">"is_static"</span>, DataType::Boolean);
        map.insert(<span class="hljs-string">"is_const"</span>, DataType::Boolean);
        map.insert(<span class="hljs-string">"has_template"</span>, DataType::Boolean);
        map.insert(<span class="hljs-string">"access_modifier"</span>, DataType::Integer);
        map.insert(<span class="hljs-string">"is_variadic"</span>, DataType::Boolean);
        map
    };
}
</code></pre>
<p>Now let's move on to the most exciting part: the Data Provider.</p>
<h3 id="heading-the-data-provider-for-the-cc-code">The Data Provider for the C/C++ Code</h3>
<p>The data provider component is used to tell the engine how to load the target data – for example from where and on which thread – and provide these data in a format that is known by our GitQL Engine. So how we can extract that information from our C/C++ code?</p>
<p>Well, we need to get the AST after parsing the C/C++ code. So the first option is to write a C/C++ parser to parse the files and provide the AST. But this option has some problems here: it'll require a lot of hard work, as C++ is a large language. To write a parser from scratch means you need to support every new feature, and handle errors, and so on.</p>
<p>The other option is to take a well-written C/C++ parser from any Compiler that provides the parser as a library and use it to provide the AST. After some searching, I found that the Clang Compiler is well-designed and can provide the parser as a library to use it to build other tools such as code formatter and linter.</p>
<p><strong>LibClang</strong> is written in C++ so I used binding for the Rust Programming language to parse the source file as a <a target="_blank" href="https://en.wikipedia.org/wiki/Translation_unit_%28programming%29"><strong>TranslationUnit</strong></a>. This is the parent node that contains information about classes, functions, and so on.</p>
<p>LibClang provides more than one way to visit the <a target="_blank" href="https://en.wikipedia.org/wiki/Translation_unit_%28programming%29">TranslationUnit</a> and all of the children of it. One of them is using the <code>clang_visitChildren</code> function. It takes a function pointer that gives you the Node and its parent and returns the flag as <code>int</code>. Using this flag, you can control if you want to break, continue, or walk inside this node using the return type.</p>
<p>For example if you are visiting the Class or Struct node and want to visit the methods inside them, you need to return <code>CXChildVisit_Recurse</code> – and <code>clang_visitChildren</code> will provide the methods for you. But if you want to just read class info then you need to return <code>CXChildVisit_Continue</code> to continue to other nodes. Using those flags in the wrong way can lead to performance issues and visiting many nodes that aren't useful.</p>
<p>So to get a function's info, we need to call <code>clang_visitChildren</code> as we pass a pointer to our data to save the information we got. For example:</p>
<pre><code class="lang-python">let mut functions: Vec&lt;FunctionNode&gt; = Vec::new();
let data = &amp;mut functions <span class="hljs-keyword">as</span> *mut Vec&lt;FunctionNode&gt; <span class="hljs-keyword">as</span> *mut c_void;

let cursor = clang_getTranslationUnitCursor(translation_unit);
clang_visitChildren(cursor, visit_children, data);
</code></pre>
<p>We passed <code>visit_children</code> that point to the function that extracts the C/C++ function's information. It will look like this:</p>
<pre><code class="lang-python">extern <span class="hljs-string">"C"</span> fn visit_children(
    cursor: CXCursor,
    parent: CXCursor,
    data: *mut c_void,
) -&gt; CXChildVisitResult {

    let cursor_kind = clang_getCursorKind(cursor);
    <span class="hljs-keyword">if</span> cursor_kind == CXCursor_FunctionDecl
        || cursor_kind == CXCursor_CXXMethod
        || cursor_kind == CXCursor_FunctionTemplate
    {
        let function_name = clang_getCursorSpelling(cursor);
        let function_type = clang_getCursorType(cursor);
        let result_type = clang_getResultType(function_type);
        let arguments_count = clang_getNumArgTypes(function_type);

        // ... Extracing more <span class="hljs-keyword">and</span> more information

        <span class="hljs-keyword">return</span> CXChildVisit_Continue
    }

    CXChildVisit_Recurse
}
</code></pre>
<p>Also, if you want to refactor or build advanced searching tools on top of ClangQL, you'll need to get the source code location. For example, where exactly does the function you're searching for exist – on which file and line?</p>
<p>So to get them from Clang, you can use the below code. It provides the file name, line, column and offset data of the selected node:</p>
<pre><code class="lang-python">let cursor_location = clang_getCursorLocation(cursor);

let mut file: CXFile = std::ptr::null_mut();
let mut line: u32 = <span class="hljs-number">0</span>;
let mut column: u32 = <span class="hljs-number">0</span>;
let mut offset: u32 = <span class="hljs-number">0</span>;

clang_getFileLocation(
    cursor_location,
    &amp;mut file,
    &amp;mut line,
    &amp;mut column,
    &amp;mut offset,
);

let file_name = clang_getFileName(file);
let file_name_str = CStr::from_ptr(clang_getCString(file_name)).to_string_lossy();
</code></pre>
<p>The source code of <code>visit_children</code> is too large to include because, as you can see, the function node contains a lot of information. So you can check the full and updated code for all visitors from this file in the ClangQL repository: <a target="_blank" href="https://github.com/AmrDeveloper/ClangQL/tree/master/src/visitor">DataProviderFile</a>.</p>
<p>The LibClang creators provide clear <a target="_blank" href="https://clang.llvm.org/docs/LibClang.html">documentation</a> on how to walk through the Translation Unit and extract the needed data.</p>
<p>So now we have our Data Schema and Provider, and we can perform a query like <code>SELECT * FROM functions</code>. The result will be likes this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/clangql_demo.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The result of running a query to select all function information from one file</em></p>
<p>So after that I decided to name the project ClangQL which stands for Clang Query Language. Now I'm working on extracting more and more important information from the AST (feel free to contribute).</p>
<p>You can find the full source code with all customizations in the <a target="_blank" href="https://github.com/AmrDeveloper/ClangQL">ClangQL repository</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You can check out the <a target="_blank" href="https://github.com/AmrDeveloper/ClangQL">ClangQL</a> project as a full sample created only in three files.</p>
<p>If you liked the project, you could give it a star ⭐ on <a target="_blank" href="https://github.com/AmrDeveloper/GQL">GitQL</a> and <a target="_blank" href="https://github.com/AmrDeveloper/ClangQL">ClangQL</a>.</p>
<p>You can check out the <a target="_blank" href="https://amrdeveloper.github.io/GQL/">website</a> for how to download and use the project on different operating systems.</p>
<p>The project is not done yet – this is just the start. Everyone is welcome to join and contribute to the project and suggest ideas or report bugs.</p>
<p>You can sponsor my work on <a target="_blank" href="https://github.com/sponsors/AmrDeveloper">GitHub</a> ❤️.</p>
<p>Thanks for reading</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Atomics and Concurrency in C++ ]]>
                </title>
                <description>
                    <![CDATA[ By Zaid Humayun Concurrency is a programming term you'll need to be familiar with if you code in C++. It's especially relevant if you want to get more out of your available compute resources.  But concurrency comes with certain problems. Some of them... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/atomics-and-concurrency-in-cpp/</link>
                <guid isPermaLink="false">66d461c7787a2a3b05af4425</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 16 Jan 2024 23:50:05 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/pexels-pixabay-290470.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Zaid Humayun</p>
<p>Concurrency is a programming term you'll need to be familiar with if you code in C++. It's especially relevant if you want to get more out of your available compute resources. </p>
<p>But concurrency comes with certain problems. Some of them can be solved using <a target="_blank" href="https://en.wikipedia.org/wiki/Mutual_exclusion">mutexes</a>, although mutexes have their own set of <a target="_blank" href="https://stackoverflow.com/questions/74521674/why-mutex-lock-on-c-affects-multithreading-efficiency-so-badly">challenges</a>.</p>
<p>This is where <a target="_blank" href="https://stackoverflow.com/questions/52196678/what-are-atomic-operations-for-newbies">atomics</a> come in. However, atomics require an understanding of the memory model of a computer, which is a challenging topic to fully grasp.</p>
<p>This is what we'll cover in this article. Hopefully you'll gain a good understanding of how memory ordering works and how to use atomics in conjunction with memory ordering to build a lock-free queue in C++.</p>
<h2 id="heading-pre-requisites">Pre-requisites</h2>
<p>To get the most out of this guide, you need to have written some basic concurrent programs. Programming experience with C++ helps.</p>
<p>Note: If you want to actually compile the code and run it, make sure to do so with the TSan flag enabled for the CLang compiler. TSan is a reliable way of detecting data races in your code, instead of trying to repeatedly run the code in a loop hoping for a data race to occur.</p>
<h2 id="heading-getting-started">Getting Started</h2>
<p>Imagine you have some concurrent code operating on some shared data in memory. You have two threads or processes, one writing and one reading on some shared piece of state.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/processes-shared-memory.jpeg" alt="Image" width="600" height="400" loading="lazy">
<em>Processes sharing memory</em></p>
<p>The "safe" way of dealing with this is mutexes. But mutexes tend to add overhead. Atomics are a more performant but much more complicated way of dealing with concurrent operations.</p>
<h2 id="heading-what-are-atomics-in-c">What Are Atomics in C++?</h2>
<p>This section is very simple. Atomics are simply operations or instructions that cannot be split by the compiler or the CPU or re-ordered in any way.</p>
<p>The simplest possible example of an atomic in C++ is an atomic flag. It looks like this:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;atomic&gt;</span></span>

<span class="hljs-function"><span class="hljs-built_in">std</span>::atomic&lt;<span class="hljs-keyword">bool</span>&gt; <span class="hljs-title">flag</span><span class="hljs-params">(<span class="hljs-literal">false</span>)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
  flag.store(<span class="hljs-literal">true</span>);
  assert(flag.load() == <span class="hljs-literal">true</span>);
}
</code></pre>
<p>We define an atomic boolean, initialise it, and then call <code>store</code> on it. This method sets the value on the flag. You can then <code>load</code> the flag from memory and assert its value.</p>
<h3 id="heading-operations-with-atomics">Operations with Atomics</h3>
<p>The operations you can perform with atomics are straightforward:</p>
<ol>
<li>You can store some value into them with the <code>store()</code> method. This is a write operation.</li>
<li>You can load some value from them with the <code>load()</code> method. This is a read operation.</li>
<li>You can do a Compare-and-Set (CAS) with them using the <code>compare_exchange_weak()</code> or <code>compare_exchange_strong()</code> method. This is a read-modify-write (RMW) operation.</li>
</ol>
<p>The important thing to remember is that each of these cannot be split into separate instructions.</p>
<p>Note: There are more methods available, but this is all we need for now.</p>
<p>There are various atomics available in C++ and you can use them in combination with memory orderings.</p>
<h2 id="heading-memory-ordering">Memory Ordering</h2>
<p>This section is a lot more complicated and is the meat of the matter. There are some great references to help you understand memory ordering in more depth that I've linked at the bottom.</p>
<h3 id="heading-why-memory-ordering-matters">Why Memory Ordering Matters</h3>
<p>The compiler and CPU are capable of re-ordering your program instructions, often independently of one another. That is, your compiler can re-order instructions and your CPU can re-order instructions again. See <a target="_blank" href="https://www.reddit.com/r/cpp/comments/dh3hle/why_is_compiler_allowed_to_reorder_instructions/">this post</a> for more detail.</p>
<p>But this is only allowed if the compiler can definitely <em>not</em> establish a relationship between the two sets of instructions.</p>
<p>For instance, the below code can be re-ordered because there is no relationship between the assignment to x and the assignment to y. That is, the compiler or CPU might assign y first and then x. But, this doesn't change the semantic meaning of your program.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">int</span> y = <span class="hljs-number">5</span>;
</code></pre>
<p>On the other hand, the following code example cannot be re-ordered because the compiler cannot establish the absence of a relationship between x and y. It's pretty easy to see here because y depends on the value of x.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">int</span> y = x + <span class="hljs-number">1</span>;
</code></pre>
<p>This doesn't seem like a big problem – until there's multi-threaded code. Let's see what I mean with an example.</p>
<h3 id="heading-intuition-for-ordering">Intuition for Ordering</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cassert&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;thread&gt;</span></span>

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

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">producer</span><span class="hljs-params">()</span> </span>{
  data = <span class="hljs-number">100</span>;  <span class="hljs-comment">// Write data</span>
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">consumer</span><span class="hljs-params">()</span> </span>{
  assert(data == <span class="hljs-number">100</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-function"><span class="hljs-built_in">std</span>::thread <span class="hljs-title">t1</span><span class="hljs-params">(producer)</span></span>;
  <span class="hljs-function"><span class="hljs-built_in">std</span>::thread <span class="hljs-title">t2</span><span class="hljs-params">(consumer)</span></span>;
  t1.join();
  t2.join();
  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>The multi-threaded example above will fail to compile with TSan because there is a clear data race when thread 1 is trying to set the value of data and thread 2 is trying to read the value of data. The easy answer here is a mutex to protect the write and read of data, but there's a way to do this with an atomic boolean.</p>
<p>We loop on the atomic boolean until we find that it is set to the value we are looking for and then check the the value of <code>data</code>.</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;atomic&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cassert&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;thread&gt;</span></span>

<span class="hljs-keyword">int</span> data = <span class="hljs-number">0</span>;
<span class="hljs-function"><span class="hljs-built_in">std</span>::atomic&lt;<span class="hljs-keyword">bool</span>&gt; <span class="hljs-title">ready</span><span class="hljs-params">(<span class="hljs-literal">false</span>)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">producer</span><span class="hljs-params">()</span> </span>{
  data = <span class="hljs-number">100</span>;
  ready.store(<span class="hljs-literal">true</span>);  <span class="hljs-comment">// Set flag</span>
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">consumer</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">while</span> (!ready.load())
    ;
  assert(data == <span class="hljs-number">100</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-function"><span class="hljs-built_in">std</span>::thread <span class="hljs-title">t1</span><span class="hljs-params">(producer)</span></span>;
  <span class="hljs-function"><span class="hljs-built_in">std</span>::thread <span class="hljs-title">t2</span><span class="hljs-params">(consumer)</span></span>;
  t1.join();
  t2.join();
  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>When you compile this with TSan, it doesn't complain about any race conditions. Note: I'm going to refer back to why TSan doesn't complain here a little further on.</p>
<p>Now, I'm going to break it by adding a memory ordering guarantee to it. Just replace <code>ready.store(true);</code> with <code>ready.store(true, std::memory_order_relaxed);</code> and replace <code>while (!ready.load())</code> with <code>while (!ready.load(std::memory_order_relaxed))</code>.</p>
<p>TSan will complain that there is a data race. But, why is it complaining?</p>
<p>The issue here is that we have no order among the operations of the two threads anymore. The compiler or CPU is free to re-order instructions in the two threads. If we go back to our abstract visualisation from earlier, this is what it looks like now:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/memory-relaxed.jpeg" alt="Image" width="600" height="400" loading="lazy">
<em>Relaxed memory model ordering</em></p>
<p>The visualisation above shows us that our two processes (threads) have no way of agreeing upon the current state or the order in which that state has changed.</p>
<p>Once process 2 determines that the flag has been set to true, so it tries to read the value of <code>data</code>. But, thread 2 believes that the value of <code>data</code> has not yet changed even though it believes the value of <code>flag</code> has been set to true.</p>
<p>This is confusing because the classic model of interleaving concurrent operations doesn't apply here. In the classic model of concurrent operations, there is always some order that can be established. For instance, we can say that this is one possible scenario of operations:</p>
<pre><code>Thread <span class="hljs-number">1</span>                  Memory                  Thread <span class="hljs-number">2</span>
---------                 -------                 ---------
  |                          |                          |
  |   write(data, <span class="hljs-number">100</span>)       |                          |
  | -----------------------&gt; |                          |
  |                          |     load(ready) == <span class="hljs-literal">true</span>  |
  |                          | &lt;----------------------  |
  |                          |                          |
  |   store(ready, true)     |                          |
  | -----------------------&gt; |                          |
  |                          |                          |
  |                          |       read(data)         |
  |                          | &lt;----------------------  |
  |                          |                          |
</code></pre><p>But, the above graphic <em>assumes</em> that both threads have agreed upon some global order of events, which isn't true at all anymore! This is still confusing for me to wrap my head around.</p>
<p>In a <code>memory_order_relaxed</code> mode, two threads have no way of agreeing upon the order of operations on shared variables. From thread 1's point of view, the operations it executed were the following:</p>
<pre><code>write(data, <span class="hljs-number">100</span>)
store(ready, <span class="hljs-literal">true</span>)
</code></pre><p>However, from thread 2's point of view, the order of operations <em>it saw</em> thread 1 execute were:</p>
<pre><code>store(ready, <span class="hljs-literal">true</span>)
write(data, <span class="hljs-number">100</span>)
</code></pre><p>Without agreeing upon the order in which operations occurred on <em>shared variables</em>, it isn't safe to make changes to those variables across threads.</p>
<p>Okay, let's fix the code by replacing <code>std::memory_order_relax</code> with <code>std::memory_order_seq_cst</code>.</p>
<p>So, <code>ready.store(true, std::memory_order_relaxed);</code> becomes <code>ready.store(true, std::memory_order_seq_cst);</code> and <code>while (!ready.load(std::memory_order_relaxed))</code> becomes <code>while (!ready.load(std::memory_order_seq_cst))</code>.</p>
<p>If you run this again with TSan, there are no more data races. But why did that fix it?</p>
<h3 id="heading-memory-barrier">Memory Barrier</h3>
<p>So, we saw our problem earlier was about two threads being unable to agree upon a single view of events and we wanted to prevent that. So, we introduced a <em>barrier</em> using sequential consistency.</p>
<pre><code>Thread <span class="hljs-number">1</span>                  Memory                  Thread <span class="hljs-number">2</span>
---------                 -------                 ---------
  |                          |                          |
  |   write(data, <span class="hljs-number">100</span>)       |                          |
  | -----------------------&gt; |                          |
  |                          |                          |
  |  ================Memory Barrier===================  |
  |   store(ready, <span class="hljs-literal">true</span>)     |                          |
  | -----------------------&gt; |                          |
  |                          |   load(ready) == <span class="hljs-literal">true</span>    |                   
  |                          | &lt;----------------------  |
  |  ================Memory Barrier===================  |
  |                          |                          |
  |                          |       read(data)         |
  |                          | &lt;----------------------  |
  |                          |                          |
</code></pre><p>The memory barrier here says that nothing before the store operation and nothing after the load operation can be re-ordered. That is, thread 2 now has a guarantee that the compiler or the CPU will not place the write to data after the write to the flag in thread 1. Similarly, the read operation in thread 2 cannot be re-ordered above the memory barrier.</p>
<p>The region inside the memory barrier is akin to a critical section that a thread needs to a mutex to enter. We now have a way to synchronise the two threads on the order of events across them.</p>
<p>This brings us back to our classic model of interleaving in concurrency because we now have an order of events both threads agree upon.</p>
<h3 id="heading-types-of-memory-order">Types Of Memory Order</h3>
<p>There are 3 main types of memory order:</p>
<ol>
<li>Relaxed memory model (std::memory_order_relaxed)</li>
<li>Release-acquire memory model (std::memory_order_release and std::memory_order_acquire)</li>
<li>Sequentially consistent memory order (std::memory_order_seq_cst)</li>
</ol>
<p>We already covered 1 and 3 in the examples above. The second memory model literally lies between the other two in terms of consistency.</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;atomic&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cassert&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;thread&gt;</span></span>

<span class="hljs-keyword">int</span> data = <span class="hljs-number">0</span>;
<span class="hljs-function"><span class="hljs-built_in">std</span>::atomic&lt;<span class="hljs-keyword">bool</span>&gt; <span class="hljs-title">ready</span><span class="hljs-params">(<span class="hljs-literal">false</span>)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">producer</span><span class="hljs-params">()</span> </span>{
  data = <span class="hljs-number">100</span>;
  ready.store(<span class="hljs-literal">true</span>, <span class="hljs-built_in">std</span>::memory_order_release);  <span class="hljs-comment">// Set flag</span>
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">consumer</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">while</span> (!ready.load(<span class="hljs-built_in">std</span>::memory_order_acquire))
    ;
  assert(data == <span class="hljs-number">100</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-function"><span class="hljs-built_in">std</span>::thread <span class="hljs-title">t1</span><span class="hljs-params">(producer)</span></span>;
  <span class="hljs-function"><span class="hljs-built_in">std</span>::thread <span class="hljs-title">t2</span><span class="hljs-params">(consumer)</span></span>;
  t1.join();
  t2.join();
  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>The above is the same example from earlier, expect with <code>std::memory_order_release</code> used for <code>ready.store()</code> and <code>memory_order_acquire</code> used for <code>read.load()</code>. The intuition here for ordering is similar to the pervious memory barrier example.</p>
<p>Except, this time the memory barrier is formed on the pair of <code>ready.store()</code> and <code>ready.load()</code> operations and will only work when used on the <em>same</em> atomic variable across threads. </p>
<p>Assuming you have a variable <code>x</code> being modified across 2 threads, you could do <code>x.store(std::memory_order_release)</code> in thread 1 and <code>x.load(std::memory_order_acquire)</code> in thread 2 and you would have a synchronization point across the two threads on this variable.</p>
<p>The difference between the sequentially consistent model and the release-acquire model is that the former enforces a global order of operations across all threads, while the latter enforces an order only among pairs of release and acquire operations.</p>
<p>Now, we can revisit why TSan didn't complain about a data race initially when there was no memory order specified. It's because C++ by default assumes a <code>std::memory_order_seq_cst</code> when no memory order is specified. Since this is the strongest memory mode, there is no data race possible.</p>
<h2 id="heading-hardware-considerations">Hardware Considerations</h2>
<p>Different memory models have different performance penalties on different hardware.</p>
<p>For instance, the x86 architectures instruction set implements something called total store ordering (TSO). The gist of it is that the model resembles all threads reading and writing to a shared memory. You can read more about that <a target="_blank" href="https://research.swtch.com/hwmm#:~:text=x86%20Total%20Store%20Order%20(x86,in%20a%20local%20write%20queue.)">here</a>.</p>
<p>This means that the x86 processors can provide sequential consistency for a relatively low computational penalty.</p>
<p>On the other side are the ARM family of processors has a weakly ordered instruction set architecture. This is because each thread or process reads and writes to its own memory. Again, the link above provides context.</p>
<p>This means that the ARM processors provide sequential consistency for a much higher computational penalty.</p>
<h2 id="heading-how-to-build-a-concurrent-queue">How to Build a Concurrent Queue</h2>
<p>I'm going to use the operations we have discussed so far to build the basic operations of a lock-free concurrent queue. This is by no means even a complete implementation, just my attempt to re-create something basic using atomics.</p>
<p>I'm going to represent the queue using a linked list and wrap each node inside an atomic.</p>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">lock_free_queue</span> {</span>
 <span class="hljs-keyword">private</span>:
  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">node</span> {</span>
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">shared_ptr</span>&lt;T&gt; data;
    <span class="hljs-built_in">std</span>::atomic&lt;node*&gt; next;

    node() : next(<span class="hljs-literal">nullptr</span>) {}  <span class="hljs-comment">//  initialise the node</span>
  };

  <span class="hljs-built_in">std</span>::atomic&lt;node*&gt; head;
  <span class="hljs-built_in">std</span>::atomic&lt;node*&gt; tail;
}
</code></pre>
<p>Now, for the enqueue operation, this is what it's going to look like:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">enqueue</span><span class="hljs-params">(T value)</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">shared_ptr</span>&lt;T&gt; new_data = <span class="hljs-built_in">std</span>::make_shared&lt;T&gt;(value);
    node* new_node = <span class="hljs-keyword">new</span> node();
    new_node-&gt;data = new_data;

    <span class="hljs-comment">//  do an infinite loop to change the tail</span>
    <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
      node* current_tail = <span class="hljs-keyword">this</span>-&gt;tail.load(<span class="hljs-built_in">std</span>::memory_order_acquire);
      node* tail_next = current_tail-&gt;next;

      <span class="hljs-comment">//  everything is correct so far, attempt the swap</span>
      <span class="hljs-keyword">if</span> (current_tail-&gt;next.compare_exchange_strong(
              tail_next, new_node, <span class="hljs-built_in">std</span>::memory_order_release)) {
        <span class="hljs-keyword">this</span>-&gt;tail = new_node;
        <span class="hljs-keyword">break</span>;
      }
    }
  }
</code></pre>
<p>The main focus is on the <code>load</code> and <code>compare_exchange_strong</code> operations. The <code>load</code> works with an <code>acquire</code> and the CAS works with a <code>release</code> so that reads and writes to the tail are synchronized.</p>
<p>Similarly for the dequeue operation:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">shared_ptr</span>&lt;T&gt; <span class="hljs-title">dequeue</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">shared_ptr</span>&lt;T&gt; return_value = <span class="hljs-literal">nullptr</span>;

    <span class="hljs-comment">//  do an infinite loop to change the head</span>
    <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
      node* current_head = <span class="hljs-keyword">this</span>-&gt;head.load(<span class="hljs-built_in">std</span>::memory_order_acquire);
      node* next_node = current_head-&gt;next;

      <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>-&gt;head.compare_exchange_strong(current_head, next_node,
                                             <span class="hljs-built_in">std</span>::memory_order_release)) {
        return_value.swap(next_node-&gt;data);
        <span class="hljs-keyword">delete</span> current_head;
        <span class="hljs-keyword">break</span>;
      }
    }
    <span class="hljs-keyword">return</span> return_value;
  }
</code></pre>
<p>Note: This queue doesn’t handle the <a target="_blank" href="https://en.wikipedia.org/wiki/ABA_problem">ABA problem</a>. It's out of the scope of this tutorial to bring in hazard pointers, so I’m leaving that out – but you can look into them if you're curious.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>So there you have it – atomics in C++. They're difficult to reason about but give you massive performance benefits. If you want to see production grade implementations of lock-free data structures, you can read more <a target="_blank" href="https://github.com/DNedic/lockfree">here</a>.</p>
<p>Typically, you'd see lock-based concurrent data structures put into production, but there is increasing research around the area of lock-free and wait-free implementations of concurrent algorithms to improve compute efficiency.</p>
<p>If you want to read this and other tutorials, you can visit my website <a target="_blank" href="https://redixhumayun.github.io/systems/2024/01/03/atomics-and-concurrency.html">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ C++ Tutorial – What Are the constexpr and constinit Specifiers? ]]>
                </title>
                <description>
                    <![CDATA[ When we write programs, many operations which are performed at runtime can actually be done at compile time – that is, baked into code.  This improves program performance since operations are no longer being computed on the fly, during runtime.  Whil... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/cpp-constexpr-and-constinit/</link>
                <guid isPermaLink="false">66b99d54c39234149cf01149</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jayant Chowdhary ]]>
                </dc:creator>
                <pubDate>Mon, 11 Dec 2023 18:50:12 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/ConstCover-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When we write programs, many operations which are performed at runtime can actually be done at compile time – that is, baked into code. </p>
<p>This improves program performance since operations are no longer being computed on the fly, during runtime. </p>
<p>While these techniques of offloading operations to compile time improve performance, they can also help subtle problems such as a the 'Static initialization Order Fiasco' which I covered in a previous <a target="_blank" href="https://www.freecodecamp.org/news/cpp-static-initialization-order-fiasco/">article</a>.  </p>
<p>This tutorial teaches you two ways to make this happen in C++. Here is what we'll cover:</p>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#heading-how-to-evaluate-functions-at-compile-time-using-constexpr">How to evaluate functions at compile time using <code>constexpr</code></a></li>
<li><a class="post-section-overview" href="#heading-the-constinit-specifier-and-its-uses">The <code>constinit</code> specifier and its uses</a></li>
<li><a class="post-section-overview" href="#heading-summary">Summary</a></li>
</ul>
<p>##Prerequisites</p>
<ul>
<li>A basic understanding of C++: For readers not familiar with C++, <a target="_blank" href="https://www.freecodecamp.org/news/learn-c-with-free-31-hour-course/">Learn C++ Programming for Beginners – Free 31-Hour Course</a> is a helpful resource</li>
<li>A read through of my previous article <a target="_blank" href="https://www.freecodecamp.org/news/cpp-static-initialization-order-fiasco/">What is the Static Initialization Order Fiasco in C++</a> will benefit you with context around <code>constinit</code>.</li>
</ul>
<h2 id="heading-how-to-evaluate-functions-at-compile-time-using-constexpr">How to Evaluate Functions at Compile Time Using <code>constexpr</code></h2>
<p>To understand this, let's first take a look at an example of a function which performs a very simple computation:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add2</span><span class="hljs-params">(<span class="hljs-keyword">int</span> input)</span> </span>{
    <span class="hljs-keyword">return</span> input + <span class="hljs-number">2</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> b = add2(<span class="hljs-number">3</span>);
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"b = "</span> &lt;&lt; b;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Here, all that the function <code>add2()</code> does is it adds 2 to the input. In <code>main()</code>, <code>add2()</code> was called with input <code>2</code>. So, it's pretty straightforward for anyone looking at the program to tell what the output of the function is going to be: 5. There is no sort of non-determinism here. </p>
<p>But if we look at the x86 assembly code generated by the compiler it would look similar to the below:</p>
<pre><code>add2(int):
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp<span class="hljs-number">-4</span>], edi
        mov     eax, DWORD PTR [rbp<span class="hljs-number">-4</span>]
        add     eax, <span class="hljs-number">2</span>
        pop     rbp
        ret
.LC0:
        .string <span class="hljs-string">"b = "</span>
<span class="hljs-attr">main</span>:
        push    rbp
        mov     rbp, rsp
        sub     rsp, <span class="hljs-number">16</span>
        mov     edi, <span class="hljs-number">3</span>
        <span class="hljs-comment">// Function add2() getting called</span>
        call    add2(int)
        mov     DWORD PTR [rbp<span class="hljs-number">-4</span>], eax
        mov     esi, OFFSET FLAT:.LC0
        mov     edi, OFFSET FLAT:_ZSt4cout
        call    std::basic_ostream&lt;char, <span class="hljs-attr">std</span>::char_traits&lt;char&gt; &gt;&amp; std::operator&lt;&lt; &lt;std::char_traits&lt;char&gt; &gt;(std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;&amp;, char const*)
        mov     rdx, rax
        mov     eax, DWORD PTR [rbp-4]
        mov     esi, eax
        mov     rdi, rdx
        call    std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;::operator&lt;&lt;(int)
        mov     eax, 0
        leave
        ret
</code></pre><p>(Note that the reference assembly codes in this article were generated by using the compiler explorer tool at <a target="_blank" href="https://godbolt.org/">godbolt.org</a>.)</p>
<p>The function <code>add2()</code> actually gets called at runtime in <code>main()</code> with the <code>call add2(int)</code> line. </p>
<p>Since this function does something that can be completely computed before the program actually executes (2+3 = 5, even in our heads!), wouldn't it be cool if we could have the compiler not create a function for this operation and just fill in the answer directly in assembly code? This is exactly what <code>constexpr</code> does. </p>
<p>If the code was changed to this:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">constexpr</span> <span class="hljs-keyword">int</span> <span class="hljs-title">add2</span><span class="hljs-params">(<span class="hljs-keyword">int</span> input)</span> </span>{
    <span class="hljs-keyword">return</span> input +<span class="hljs-number">2</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> b = add2(<span class="hljs-number">3</span>);
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"b = "</span> &lt;&lt; b;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>the compiler would output the following assembly code:</p>
<pre><code>.LC0:
        .string <span class="hljs-string">"b = "</span>
<span class="hljs-attr">main</span>:
        push    rbp
        mov     rbp, rsp
        sub     rsp, <span class="hljs-number">16</span>
        mov     DWORD PTR [rbp<span class="hljs-number">-4</span>], <span class="hljs-number">5</span>
        mov     esi, OFFSET FLAT:.LC0
        mov     edi, OFFSET FLAT:_ZSt4cout
        call    std::basic_ostream&lt;char, <span class="hljs-attr">std</span>::char_traits&lt;char&gt; &gt;&amp; std::operator&lt;&lt; &lt;std::char_traits&lt;char&gt; &gt;(std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;&amp;, char const*)
        mov     rdx, rax
        mov     eax, DWORD PTR [rbp-4]
        mov     esi, eax
        mov     rdi, rdx
        call    std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;::operator&lt;&lt;(int)
        mov     eax, 0
        leave
        ret
</code></pre><p>The function <code>add2()</code> has disappeared and the line <code>mov DWORD PTR [rbp-4], 5</code> has baked into the program the evaluation of the function <code>add2()</code> at compile time. There is no runtime call to <code>add2()</code>. </p>
<p>Mind you, this is possible since we've passed in 3 – an expression that is known at compile time – to the <code>add2()</code> function. If something that couldn't be evaluated at compile time was passed in, the compiler would again generate an <code>add2()</code> function. </p>
<p>You can see what I mean in this snippet:</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;random&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">constexpr</span> <span class="hljs-keyword">int</span> <span class="hljs-title">add2</span><span class="hljs-params">(<span class="hljs-keyword">int</span> input)</span> </span>{
    <span class="hljs-keyword">return</span> input +<span class="hljs-number">2</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> rd = <span class="hljs-built_in">std</span>::rand();
    <span class="hljs-keyword">int</span> b = add2(rd);
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"b = "</span> &lt;&lt; b;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>The assembly generated again has the <code>add2()</code> function:</p>
<pre><code>add2(int):
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp<span class="hljs-number">-4</span>], edi
        mov     eax, DWORD PTR [rbp<span class="hljs-number">-4</span>]
        add     eax, <span class="hljs-number">2</span>
        pop     rbp
        ret
.LC0:
        .string <span class="hljs-string">"b = "</span>
<span class="hljs-attr">main</span>:
        push    rbp
<span class="hljs-comment">// Snip</span>
</code></pre><p>Alright, you've now seen how using the <code>constexpr</code> specifier can help programs move runtime costs to compile time costs in many cases. </p>
<p>Let's now look at another specifier introduced recently, in C++20, which verifies that variables are initialized at compile time.</p>
<h2 id="heading-the-constinit-specifier-and-its-uses">The <code>constinit</code> Specifier and its Uses</h2>
<p>The <a target="_blank" href="https://en.cppreference.com/w/cpp/language/constant_initialization"><code>constinit</code></a> specifier was introduced in C++ 20. This specifier <em>asserts</em> that a variable has constant initialization – it <a target="_blank" href="https://en.cppreference.com/w/cpp/language/constant_initialization">sets the initial values of the static variables to a compile-time constant</a>. Otherwise, the program is ill-formed and the compiler produces an error. For example:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add2</span><span class="hljs-params">(<span class="hljs-keyword">int</span> v)</span> </span>{
    <span class="hljs-keyword">return</span> v + <span class="hljs-number">2</span>;
}

<span class="hljs-comment">//Error: 'constinit' variable 'glob' does not have a constant initializer  </span>
<span class="hljs-keyword">constinit</span> <span class="hljs-keyword">int</span> glob = add2(<span class="hljs-number">2</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">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>The compiler errors out here since the <code>add2()</code> function isn't <em>sure</em> to have constant initialization – which can be determined at compile time. Now if the <code>add2()</code> function is marked <code>constexpr</code>, it will have constant initialization, so the code compiles.</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">constexpr</span> <span class="hljs-keyword">int</span> <span class="hljs-title">add2</span><span class="hljs-params">(<span class="hljs-keyword">int</span> v)</span> </span>{
    <span class="hljs-keyword">return</span> v + <span class="hljs-number">2</span>;
}

<span class="hljs-comment">//OKAY 'constinit' variable 'glob' does have a constant initializer.  </span>
<span class="hljs-keyword">constinit</span> <span class="hljs-keyword">int</span> glob = add2(<span class="hljs-number">2</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">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Now you may ask – what's really the use of this specifier?</p>
<p>The answer is it that can be used in certain cases to solve the 'Static Initialization Order Fiasco'. </p>
<p>I talked about the 'Static Initialization order Fiasco' in an <a target="_blank" href="https://www.freecodecamp.org/news/cpp-static-initialization-order-fiasco/">earlier article</a>. If we use <code>constinit</code>, the compiler is giving the programmer its word that the <code>constinit</code> variable will be constant initialized – so that's before any other static variables are constructed at runtime. We get rid of the 'Static Initialization / Destruction Order Fiasco'. </p>
<p>Another example where we use strings that are constant initialized illustrates this:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Parent.h</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Parent</span> {</span>
    <span class="hljs-keyword">public</span>:
       <span class="hljs-function"><span class="hljs-keyword">size_t</span> <span class="hljs-title">getMoneyCount</span><span class="hljs-params">()</span></span>;
       <span class="hljs-function"><span class="hljs-keyword">constexpr</span> <span class="hljs-title">Parent</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span> *moneyString)</span>: <span class="hljs-title">mData</span><span class="hljs-params">(moneyString)</span> </span>{};
    <span class="hljs-keyword">private</span>:
        <span class="hljs-built_in">std</span>::string_view mData;     
};
<span class="hljs-keyword">extern</span> Parent everyonesParent;

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

<span class="hljs-function"><span class="hljs-keyword">constinit</span> <span class="hljs-keyword">static</span> Parent <span class="hljs-title">everyonesParent</span><span class="hljs-params">(<span class="hljs-string">"TheParent"</span>)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">size_t</span> <span class="hljs-title">Parent::getMoneyCount</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> mData.size();
}

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

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Child</span> {</span>
    <span class="hljs-keyword">public</span>:
    Child(Parent &amp;parent) : mMoneyCount(parent.getMoneyCount()) {};
    <span class="hljs-keyword">private</span>:
    <span class="hljs-keyword">size_t</span> mMoneyCount;
};

<span class="hljs-function"><span class="hljs-keyword">static</span> Child <span class="hljs-title">everyonesChild</span><span class="hljs-params">(everyonesParent)</span></span>;
</code></pre>
<p>There is no static initialization order problem here, since the static object <code>everyonesParent</code> is guaranteed to be initialized before <code>everyonesChild</code>, since it was marked <code>constinit</code>. </p>
<p>It was okay to mark <code>everyonesParent</code> <code>constinit</code> since it used <code>std::string_view</code> which can be constant initialized – unlike <code>std::string</code>. Also, it had a <code>constexpr</code> constructor. If it didn't use either of these, compilation would have failed!</p>
<p>In closing, something to note about <code>constinit</code>: <code>constinit</code> does not imply <code>const</code>.</p>
<p><code>constinit</code> values can be modified after construction. Take this example – it is perfectly legal:</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">constinit</span> <span class="hljs-keyword">int</span> i = <span class="hljs-number">42</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
 i++;
 <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">" i is "</span> &lt;&lt; i &lt;&lt; <span class="hljs-string">"\n"</span>;
}
</code></pre>
<p>##Summary</p>
<p>This article covered compile time operations and run time operations. It analyzed how compilers produce code to either generate functions used at runtime or evaluate them at compile time. </p>
<p>You learned about the <code>constexpr</code> and <code>constinit</code> specifiers in C++, and how they are extremely useful.</p>
<p>I hope you enjoyed the article!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is the Static Initialization Order Fiasco in C++? [Solved] ]]>
                </title>
                <description>
                    <![CDATA[ In this article, I'll be covering a subtle but egregious problem that can occur in C++ programs. This problem is popularly called the 'Static Initialization Order Fiasco'.  I'll first go over what the problem is, then go onto some solutions and explo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/cpp-static-initialization-order-fiasco/</link>
                <guid isPermaLink="false">66b99d5865fc624db0255e09</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jayant Chowdhary ]]>
                </dc:creator>
                <pubDate>Wed, 06 Dec 2023 23:11:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/StaticCover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, I'll be covering a subtle but egregious problem that can occur in C++ programs. This problem is popularly called the 'Static Initialization Order Fiasco'. </p>
<p>I'll first go over what the problem is, then go onto some solutions and explore how they work. Let's get started. </p>
<p>This is what we'll cover:</p>
<ul>
    <li><a href="#prerequisites">Prerequisites</a></li>
    <li><a href="#whatisthestaticinitializationorderfiascoinc">What is the 'Static Initialization Order Fiasco' in C++ ?</a></li>
     <li><a href="#solutionstothestaticdeinitializationorderproblem">Solutions to the static de-initialization order problem</a>
          </li><li><a href="#constructonfirstuseidiom">Construct on first use idiom</a></li>
    <li><a href="#niftycountersolution">Nifty Counter Solution</a></li>
    
    <li><a href="#summary"> Summary</a></li>
</ul>

<p>##Prerequisites</p>
<ul>
<li>A basic understanding of C++: For readers not familiar with C++, <a target="_blank" href="https://www.freecodecamp.org/news/learn-c-with-free-31-hour-course/">Learn C++ Programming for Beginners – Free 31-Hour Course</a> is a helpful resource</li>
<li>In particular, an understanding of <a target="_blank" href="https://learn.microsoft.com/en-us/cpp/cpp/storage-classes-cpp?view=msvc-170">storage classes</a> in C++ will be helpful.</li>
</ul>
<p>##What is the 'Static Initialization Order Fiasco' in C++ ?</p>
<p>The C++ standard states: </p>
<blockquote>
<p><em>"The order in which static objects are initialized across different translation units is <a target="_blank" href="https://en.cppreference.com/w/cpp/language/siof">undefined</a> or ambiguous</em>."</p>
</blockquote>
<p>A translation unit is just a way of saying a file that is fed into the compiler. It's a C++ source file with all the code from the headers included in it. </p>
<p>One thing to note though, for later in the article: static objects in the same translation unit are constructed in order of declaration and destructed in the reverse order.</p>
<p>So, how is this a problem?</p>
<p>It can be a problem in the following situation:</p>
<p>Let's say there are 2 static objects in 2 different files. <code>File1.cpp</code> has a static object of type class A – <code>aObj</code> . <code>File2.cpp</code> has a static object of type class B – <code>bObj</code>. The static object in <code>File1.cpp</code> is visible to <code>File2.cpp</code> since it declares <code>aObj</code> as <code>extern</code> in <code>File1.h</code>.</p>
<pre><code class="lang-cpp">
<span class="hljs-comment">// Static initialization order problem</span>
<span class="hljs-comment">// File1.h</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> {</span>
....
  <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span> </span>{
    ...
  } 
}
<span class="hljs-keyword">extern</span> A aObj;

<span class="hljs-comment">//File1.cpp</span>


<span class="hljs-keyword">static</span> A aObj;

<span class="hljs-comment">// File2.cpp</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> {</span>
B() {
 aObj.doSomething();<span class="hljs-comment">// Not okay! aObj may not have been constructed</span>
}
....
}

<span class="hljs-keyword">static</span> B bObj;
</code></pre>
<p>In this program, it is possible that the object <code>aObj</code> in File1.cpp gets initialized before <code>bObj</code> in File2.cpp. That is all good since in that case, the constructor for <code>bObj</code> runs after <code>aObj</code> has been constructed. It is safe to call call methods on <code>aObj</code>.</p>
<p>But it is also possible that the object <code>bObj</code> in File2.cpp gets initialized before <code>aObj</code> in File1.cpp. In that case, <em>the constructor of</em> <code>bObj</code> <em>calls</em> <code>doSomething()</code> <em>on</em> <code>aObj</code> <em>which has not been constructed!</em> The memory has been allocated for <code>aObj</code>, but it hasn't been constructed. This could lead to unintended behavior / a corrupt program.</p>
<p>So this is what the static initialization order fiasco is all about. </p>
<p>But we're not done: the other problem is the <strong>static de-initialization order fiasco</strong>! This is pretty much the same problem, just applied to the order of de-initialization of static objects. </p>
<p>The C++ standard doesn't specify the order in which static objects get de-initialized as well. So it is possible that static object <code>aObj</code> gets destroyed before <code>bObj</code>. This is a problem if <code>bObj</code>'s destructor uses or references <code>aObj</code>. </p>
<p>This is illustrated in the code snippet below – it is pretty much the same as the example above, just that its the de-initialization order which is dangerous this time:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Static de-initialization order problem</span>
<span class="hljs-comment">// File1.h</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> {</span>
....
  <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span> </span>{
    ...
  } 
}
<span class="hljs-keyword">extern</span> A aObj;

<span class="hljs-comment">//File1.cpp</span>

<span class="hljs-keyword">static</span> A aObj;

<span class="hljs-comment">// File2.cpp</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> {</span>
B() {}
~B() {
 aObj.doSomething(); <span class="hljs-comment">// Not okay! aObj may have already been destructed!</span>
}
....
}

<span class="hljs-keyword">static</span> B bObj;
</code></pre>
<p><strong>Note:</strong> These problems are only applicable to objects with <em>static</em> storage scope. They won't occur if <code>bObj</code> was a variable with automatic storage scope. In that case, the C++ standard guarantees that <code>aObj</code> is constructed before <code>bObj</code> and destructed after it.</p>
<p><strong>Another note:</strong> These problems also do not occur in C programs. Why is that so? Well in C, there's no concept of constructors and destructors. Static objects are completely defined during compile time.</p>
<h2 id="heading-how-to-solve-the-static-de-initialization-order-problem">How to Solve the Static De-initialization Order Problem</h2>
<p>Now that it is clear what the problem is, I will discuss some solutions. There are multiple ways of solving this problem – each with its tradeoffs. Let's take a look.</p>
<p>###Construct on first use idiom:</p>
<p>This idiom tries to make sure that there is always a fully constructed object whenever the static object in question is used. Following the examples in the previous section, we can do this by replacing all references to <code>aObj</code> by a function call <code>aObj()</code> which returns a reference to an object of type <code>A</code>. </p>
<p>In code it looks like this:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Static initialization order problem</span>
<span class="hljs-comment">// File1.h</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> {</span>
....
  <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span> </span>{
    ...
  } 
};

<span class="hljs-function">A&amp; <span class="hljs-title">aObj</span><span class="hljs-params">()</span></span>;

<span class="hljs-comment">//File1.cpp</span>

<span class="hljs-function">A&amp; <span class="hljs-title">aObj</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">static</span> A *aObj = <span class="hljs-keyword">new</span> A();
  <span class="hljs-keyword">return</span> *aObj; 
}

<span class="hljs-comment">// File2.cpp</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> {</span>
 B() {
   <span class="hljs-comment">/*
    * Okay since calling aObj() gaurantees that
    * static A *aObj = new A(); ran
    */</span>
   aObj().doSomething();  
  }
  ....
};

<span class="hljs-keyword">static</span> B bObj;
</code></pre>
<p><code>bObj</code> can safely assume that calling aObj() returns a fully constructed <code>aObj</code> since this line:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">static</span> A *aObj = <span class="hljs-keyword">new</span> A();
</code></pre>
<p>would have run on the function call and will give it a fully constructed object. Also, since the program never calls delete on <code>aObj</code>, it is never destructed so it is also safe to use <code>aObj</code> in <code>bObj</code>'s destructor. </p>
<p>But this does mean that the memory allocated for <code>aObj</code> always stays alive and valid throughout the lifetime of the program. And this may or may not be a problem (it does get reclaimed by the OS after the program exits, of course).</p>
<p>So, in which situation is this solution not great? In the case that <code>aObj</code>'s destructor does something desirable. For example: when <code>aObj</code> gets destructed – it writes to a log file / does something else that has some side effects.</p>
<p>Now you may ask, okay, why don't just I replace the static pointer in the <code>aObj()</code> function call with a static <code>aObj</code> object?</p>
<pre><code class="lang-cpp"><span class="hljs-function">A&amp; <span class="hljs-title">aObj</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">static</span> A aObj;
  <span class="hljs-keyword">return</span> aObj; 
}
</code></pre>
<p>That still ensures that <code>aObj</code> has been fully constructed by the time the function is called right? Right. But it does not save us from the static de-initialization order problem. It is still possible that <code>aObj</code>'s destructor runs before <code>bObj</code> 's destructor.</p>
<p>There is an interesting trick that solves both of these problems: The Nifty Counter Idiom.</p>
<p>###Nifty Counter Solution</p>
<p>Reference: this resource on the <a target="_blank" href="https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter#:~:text=The%20%22nifty%20counter%22%20or%20%22,the%20initialization%20of%20static%20objects.&amp;text=The%20header%20file%20of%20the,called%20on%20the%20Stream%20object.">Nifty counter idiom</a> presents the idea behind this idiom. Let's examine it.</p>
<p>The idea is to ensure that:</p>
<ol>
<li>The static object being used gets constructed before any other static object in the translation unit that it is being used in.</li>
<li>The static object being used gets destructed after any other static object in the translation unit that it is being used in.</li>
</ol>
<pre><code class="lang-cpp"><span class="hljs-comment">// File1.h</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">A</span> {</span>
  A();
  ~A();
};
<span class="hljs-keyword">extern</span> A&amp; aObj;

<span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">AInitializer</span> {</span>
  AInitializer ();
  ~AInitializer ();
} aInitializer; <span class="hljs-comment">// static initializer for every translation unit that aObj is used in</span>
</code></pre>
<pre><code class="lang-cpp"><span class="hljs-comment">// File1.cpp</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"File1.h"</span></span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;new&gt;         // Used for placement new</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;type_traits&gt; // Used for aligned_storage</span></span>

<span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> niftyCounter; <span class="hljs-comment">// this is zero initialized at load time</span>

<span class="hljs-comment">/*
 * Memory for the static object aObj - memory itself is valid throughout the
 * the lifetime of the program.
 */</span>
<span class="hljs-keyword">static</span> <span class="hljs-keyword">typename</span> <span class="hljs-built_in">std</span>::aligned_storage&lt;<span class="hljs-keyword">sizeof</span> (A), <span class="hljs-keyword">alignof</span> (A)&gt;::type
  aObjBuf; 

A&amp; aObj = <span class="hljs-keyword">reinterpret_cast</span>&lt;A&amp;&gt; (aObj);

A::A ()
{
  <span class="hljs-comment">// Construct A</span>
}
A::~A ()
{
  <span class="hljs-comment">/*
   * Destruct A: with possible side effects
   * like writing to a file.
   */</span>
} 

AInitializer::AInitializer ()
{
  <span class="hljs-keyword">if</span> (niftyCounter++ == <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">new</span> (&amp;aObj) A (); <span class="hljs-comment">// use placement new operator</span>
  }
}

AInitializer::~AInitializer ()
{
  <span class="hljs-keyword">if</span> (--niftyCounter == <span class="hljs-number">0</span>) {
    (&amp;aObj)-&gt;~A(); <span class="hljs-comment">// run the destructor</span>
  }
}
</code></pre>
<p>Let's try to understand what this code does.</p>
<p>First, in the header file, <code>File1.h</code> has the definition of <code>class A</code> first. After that, is have the definition of a class called <code>AInitializer</code>. </p>
<p>There is also a static object <strong>defined</strong> in the header file of type <code>AInitializer</code>. This makes sure that the constructor for <code>AInitializer</code> runs before the constructor for any other static object in the translation unit that <code>File1.h</code> is included in (of course you have to include File1.h before any other static object's definition in source files). </p>
<p>Remember: <em>static objects in the same translation unit are constructed in order of declaration and destructed in the reverse order</em>.</p>
<p>So now that <code>AInitializer</code> is constructed before any other static objects in a translation unit, how can we use this to our advantage? <code>aObj</code> can be constructed in the constructor of <code>AInitializer</code>! Which is what is happening in the lines below:</p>
<pre><code class="lang-cpp">AInitializer::AInitializer ()
{
  <span class="hljs-keyword">if</span> (nifty_counter++ == <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">new</span> (&amp;aObj) A (); <span class="hljs-comment">// use placement new</span>
  }
}
</code></pre>
<p>Note that the <a target="_blank" href="https://en.cppreference.com/w/cpp/language/new">placement new</a> operator is being used here instead of the <code>new</code> operator to construct <code>aObj</code>. Let's see what would happen if we used <code>new</code> instead. The code would look like this:</p>
<pre><code class="lang-cpp">A&amp; aObj;
A *aObjp = <span class="hljs-literal">nullptr</span>;

AInitializer::AInitializer ()
{
  <span class="hljs-keyword">if</span> (nifty_counter++ == <span class="hljs-number">0</span>) {
    aObjp = <span class="hljs-keyword">new</span> A (); 
    aObj = *aObjp; <span class="hljs-comment">// Not okay! Cannot re-assign a reference</span>
  }
}
</code></pre>
<p>This doesn't work since a reference needs to be defined and declared at the same time. That is precisely why the placement <code>new</code> operator needs to be used.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">static</span> <span class="hljs-keyword">typename</span> <span class="hljs-built_in">std</span>::aligned_storage&lt;<span class="hljs-keyword">sizeof</span> (A), <span class="hljs-keyword">alignof</span> (A)&gt;::type
  aObjBuf; 

A&amp; aObj = <span class="hljs-keyword">reinterpret_cast</span>&lt;A&amp;&gt; (aObj)
</code></pre>
<p>This allocates memory to fit an object of type <code>A</code> and later assigns that to the reference. Now all that's left to be done is to actually <em>construct</em> the object in <code>AInitializer</code>'s constructor – which is what is done with the placement new operator.</p>
<p>Another question that may arise in your mind: here, there is a static object <code>aObjBuf</code>. But isn't that subject to the same de-initialization order problem that we talked about in the second part of the Construct <em>on first use</em> idiom? </p>
<p>The answer is that the memory for <code>aObjBuf</code> stays alive and valid until the program is alive. Nothing happens in the construction of the memory. So it's valid to this.</p>
<p>This approach also makes sure that the static de-initialization order problem isn't hit, since the last <code>AInitializer</code> object destructed will call the destructor of <code>aObj</code>. That is guaranteed to run after any static objects in other translation units run, since within the particular translation unit, the static object <code>aInitializer</code> is declared before any other static object using <code>aObj</code>. This means it will get destructed in the reverse order – that is after the destructor for any other static objects have run.</p>
<p>There are some caveats here: this solution isn't the easiest to understand and implement. This is also not thread safe. You can find more information in the article on Nifty counters presented in the The C/C++ Users Journal, May, 1999 <a target="_blank" href="http://www.petebecker.com/js/js199905.html">here</a>.</p>
<p>##Summary</p>
<p>Using statically initialized objects in C++ is tricky and should be done with care. Fortunately, there are multiple solutions and ways to get around the problem. </p>
<p>In this article, we covered some common solutions: the 'Construct on first use' idiom and the 'Nifty counter solution', along with their merits and challenges.</p>
<p>Hope you enjoyed this article!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Keeping Time in C++: How to use the std::chrono API ]]>
                </title>
                <description>
                    <![CDATA[ Keeping track of time is a very important aspect of computer programs. Some common use cases are: Measure/profile the performance of certain parts of code. Do work at certain periods of time, from within a program.  Detect whether threads are in a d... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/cpp-std-chrono-api/</link>
                <guid isPermaLink="false">66b99d5fc39234149cf0114b</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ profiling ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jayant Chowdhary ]]>
                </dc:creator>
                <pubDate>Mon, 04 Dec 2023 23:38:45 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/ClangCover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Keeping track of time is a very important aspect of computer programs. Some common use cases are:</p>
<ul>
<li>Measure/profile the performance of certain parts of code.</li>
<li>Do work at certain periods of time, from within a program. </li>
<li>Detect whether threads are in a deadlock / taking too long to complete an operation.</li>
<li>Synchronize tasks between different components of software</li>
</ul>
<p>and many more…</p>
<p>This article will guide you through how you can measure time in modern C++. </p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li>A basic understanding of C++: For readers not familiar with C++, <a target="_blank" href="https://www.freecodecamp.org/news/learn-c-with-free-31-hour-course/">Learn C++ Programming for Beginners – Free 31-Hour Course</a> is a helpful resource.</li>
<li>A quick read through Linux time tracking infrastructure – <a target="_blank" href="https://man7.org/linux/man-pages/man2/gettimeofday.2.html">such as you can find here</a> – will help you get familiar with the ideas presented in the article.</li>
</ul>
<h2 id="heading-common-ways-to-track-time-in-c">Common Ways to Track Time in C++</h2>
<p>This article covers how you can keep track of time in C++. In C, on UNIX like systems, you can use the <a target="_blank" href="https://linux.die.net/man/3/clock_gettime">clock_gettime()</a> function to keep track of time. It returns time in a structured way through the <a target="_blank" href="https://www.gnu.org/software/libc/manual/html_node/Time-Types.html"><code>timespec</code></a> struct. </p>
<p>The <a target="_blank" href="https://linux.die.net/man/3/clock_gettime"><code>clock_gettime()</code></a> /<a target="_blank" href="https://linux.die.net/man/2/gettimeofday">gettimeofday</a> function gives us back a filled <a target="_blank" href="https://www.gnu.org/software/libc/manual/html_node/Time-Types.html"><code>timespec</code></a> struct which has two fields:</p>
<ol>
<li><code>tv_sec</code>, which gives us the time in seconds since the time source – CLOCK_REALTIME / CLOCK_MONOTONIC that was passed into clock_gettime. The 'type' of this field is <a target="_blank" href="https://en.cppreference.com/w/c/chrono/time_t"><code>time_t</code></a> which is usually an integral value.</li>
<li><code>tv_nsec</code>, which gives the time after <code>tv_sec</code>, in nanoseconds since the time source that was specified while calling <code>clock_gettime()</code>. The type of this field is a long int.</li>
</ol>
<p>So why is <a target="_blank" href="https://linux.die.net/man/3/clock_gettime"><code>clock_gettime()</code></a> not good enough? The answer is that the members of <code>struct timespec</code> can easily be passed to functions as they're really just <code>int</code>s / <code>float</code>s. They're not strongly typed. </p>
<p>It's also easy to forget about the units in which they represent time while passing information around to functions. This can happen when you're dealing with projects that have thousands of lines of code.</p>
<p>So what's the solution?</p>
<p>##The std::chrono API</p>
<p>C++11 introduced the std::chrono API, which can help you avoid some of these problems.</p>
<p>There are 3 important parts of the API.</p>
<p>###1. <code>std::chrono::duration</code></p>
<p>As its name suggests, <code>std::chrono::duration</code> is a type that represents a time interval. The official C++ reference mentions that <code>std::chrono::duration</code> is a templated type with the following signature:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">template</span>&lt;
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Rep</span>,
    <span class="hljs-title">class</span> <span class="hljs-title">Period</span> = <span class="hljs-title">std</span>:</span>:ratio&lt;<span class="hljs-number">1</span>&gt;
&gt; <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">duration</span>;</span>
</code></pre>
<p>Here, the <code>Rep</code> template parameter represents the type that is used to count 'ticks' of time. A tick is just a unit of time which is a given fraction of a second. <code>Period</code>, the second parameter, defines what exactly that fraction is.</p>
<p>So, for example, if you write:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">using</span> my_ms_type = <span class="hljs-built_in">std</span>::chrono::duration&lt;<span class="hljs-keyword">int</span>, <span class="hljs-built_in">std</span>::ratio&lt;<span class="hljs-number">1</span>, <span class="hljs-number">1000</span>&gt;&gt;

my_ms_type duration_ms duration = <span class="hljs-number">3</span>; <span class="hljs-comment">// error: cannot convert from int</span>
my_ms_type duration_ms duration_ok{<span class="hljs-number">3</span>} <span class="hljs-comment">// OK, can construct from int</span>
</code></pre>
<p><code>my_ms_type</code> is a type that has been defined, which counts in units of milliseconds (1/1000th of a second). This count is expressed as an integer. As you might be able to guess, the <code>Rep</code> template parameter is <code>int</code> and Period is <code>std::ratio&lt;1,1000&gt;</code> (which really is a way of saying 1/1000).</p>
<p>Now that it's clear how durations are represented, let's see what we can and cannot do with these.</p>
<p>If there is a function that takes in a <code>my_ms_type</code> duration and you instead try to pass in any non-<code>std::chrono::duration</code> type, you'll get a compiler error.</p>
<p>It is possible to implicitly convert between different types of <code>std::chrono::duration</code> as long as information isn't lost with the type of <code>Rep</code>, since the standard library can compute the relationship between two <code>std::chrono::duration</code>types. It is not possible to implicitly convert if there is a loss of information. For example:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;chrono&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>::chrono;
<span class="hljs-keyword">using</span> my_type_ms = <span class="hljs-built_in">std</span>::chrono::duration&lt;<span class="hljs-keyword">int</span>, <span class="hljs-built_in">std</span>::ratio&lt;<span class="hljs-number">1</span>, <span class="hljs-number">1000</span>&gt;&gt;;
<span class="hljs-keyword">using</span> my_type_ms_f = <span class="hljs-built_in">std</span>::chrono::duration&lt;<span class="hljs-keyword">float</span>, <span class="hljs-built_in">std</span>::ratio&lt;<span class="hljs-number">1</span>, <span class="hljs-number">1000</span>&gt;&gt;;
<span class="hljs-keyword">using</span> my_type_hundredth_s = <span class="hljs-built_in">std</span>::chrono::duration&lt;<span class="hljs-keyword">int</span>, <span class="hljs-built_in">std</span>::ratio&lt;<span class="hljs-number">1</span>, <span class="hljs-number">100</span>&gt;&gt;;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">f</span><span class="hljs-params">(my_type_ms millis)</span> </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> duration = <span class="hljs-number">2</span>;
   my_type_ms_f duration_f{<span class="hljs-number">2.5</span>};
   my_type_hundredth_s duration_compatible{<span class="hljs-number">100</span>};

   f(duration); <span class="hljs-comment">// error: could not convert 'duration' from 'int' to 'my_type_ms'</span>

   f(duration_f) <span class="hljs-comment">//error: since float -&gt; int will lose information</span>

   f(duration_compatible) <span class="hljs-comment">// OK since no information is lost</span>
}
</code></pre>
<p>The standard library also has some predefined <code>std::chrono::duration</code> template specializations for common time durations such as <code>std::chrono::duration::seconds</code>, <code>milliseconds</code>, <code>microseconds</code>, and so on.</p>
<p>You can also get the 'count' value contained in a duration by using the <code>count</code> method in a duration.</p>
<pre><code class="lang-cpp"><span class="hljs-built_in">std</span>::chrono::seconds duration{<span class="hljs-number">3</span>};
<span class="hljs-comment">// Prints: 'Duration count: 3 seconds'</span>
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Duration count: "</span> &lt;&lt; duration.count() &lt;&lt; <span class="hljs-string">" seconds"</span>;
</code></pre>
<p>Interestingly, converting from a unit with higher precision like <code>nanosecond</code> to something with a lower precision such as <code>millisecond</code> may also lead to a loss of information. For these specific cases, you need to use an <em>explicit cast</em> for conversion. This is called <code>duration_cast</code>. For example:</p>
<pre><code class="lang-cpp">nanoseconds durationInNs = <span class="hljs-number">3000000000</span>;
seconds ms = duration_cast&lt;seconds&gt;(durationInNs); <span class="hljs-comment">//OK 3s</span>
durationInNs = <span class="hljs-number">3500000000</span>;
ms = duration_cast&lt;nanoseconds&gt;(durationInNs); <span class="hljs-comment">// OK 3s - truncates down</span>
</code></pre>
<p>Now that we know why <code>std::chrono::duration</code> is useful, let's move on. The next section explores <code>std::chrono::time_point</code>.</p>
<p>###2. <code>std::chrono::time_point</code></p>
<p><code>std::chrono::time_point</code> is a way of expressing a particular point in time – surprise, surprise! </p>
<p>If you think about it, how can you logically define a point in time ? We need to have a reference starting point and a duration from the starting point. This is exactly what <code>std::chrono::time_point</code> does. </p>
<p>The class declaration looks like this:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">template</span>&lt;
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Clock</span>,
    <span class="hljs-title">class</span> <span class="hljs-title">Duration</span> = <span class="hljs-title">typename</span> <span class="hljs-title">Clock</span>:</span>:duration
&gt; <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">time_point</span>;</span>
</code></pre>
<p>There are two template parameters here:</p>
<p>The first one is <code>Clock</code> which represents a reference clock relative to which the point in time is being measured. For now, some examples of clocks are:</p>
<ul>
<li><code>system_clock</code>: this represents a real-world wall clock. It's useful when you want to measure time in terms of real-world times. It's important to note that the system time can usually be changed on any system, so you shouldn't depend on this clock to calculate time periods between tasks / performance profiling.</li>
<li><code>steady_clock</code>: this represents a monotonically increasing clock. It's useful when you need stop-watch like clock accounting.</li>
</ul>
<p>The second template parameter is <code>Duration</code> which is what we discussed in the previous section. A <code>time_point</code> needs to be associated with a <code>duration</code> type since that's what is being used to measure ticks since the 'epoch' of the <code>Clock</code>. </p>
<p>Epoch is just a way of saying a reference point in time. While there's no mandate for which reference to use, Unix Time - that is, the time since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970 is a common one.</p>
<p>Time points based on the <em>same</em> clock can be subtracted and not added. For example:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">auto</span> tp1 = <span class="hljs-built_in">std</span>::chrono::system_clock::now();
...
<span class="hljs-keyword">auto</span> tp2 = <span class="hljs-built_in">std</span>::chrono::system_clock::now()
<span class="hljs-keyword">auto</span> tp3 = <span class="hljs-built_in">std</span>::chrono::steady_clock::now();

<span class="hljs-keyword">auto</span> diff = tp2 - tp1; <span class="hljs-comment">// OK</span>
<span class="hljs-keyword">auto</span> add = tp1 + tp2; <span class="hljs-comment">// Not Ok</span>
<span class="hljs-keyword">auto</span> add = tp3 - tp2; <span class="hljs-comment">// Not Ok - based on different clocks</span>
</code></pre>
<p>Let's now see what clocks are.</p>
<p>###3. Clock Types</p>
<p>A <code>Clock</code> is a type that ties together <code>std::chrono::duration</code> and <code>std::chrono::time_point</code>. It has a function <code>now()</code> that returns the current <code>time_point</code>. The formal requirements for a type to be a <code>Clock</code> can be found in the C++ spec <a target="_blank" href="https://en.cppreference.com/w/cpp/named_req/Clock">here</a>.</p>
<p>As mentioned before, <code>system_clock</code> and <code>steady_clock</code> are two popular clocks provided by the standard library. Each clock has its own associated <code>duration</code> as well.</p>
<p>Each <code>time_point</code> is associated with some clock, since it really has to be relative to some given reference.</p>
<p>Finally, let's see some examples of how you can tie together <code>duration</code>, <code>time_point</code>, and <code>Clock</code>. Let's say you want to measure the time that looping 100,000,000 times takes in nanoseconds, and you also want to print out the current wall time:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;chrono&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;ratio&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;thread&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;ctime&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>::chrono;
<span class="hljs-keyword">constexpr</span> <span class="hljs-keyword">size_t</span> kIterations = <span class="hljs-number">100000000</span>;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">testFunction</span> <span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">size_t</span> i = <span class="hljs-number">0</span>; i &lt; kIterations; i++) {
    }
}

<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">auto</span> tStartSteady = <span class="hljs-built_in">std</span>::chrono::steady_clock::now();
    <span class="hljs-built_in">std</span>::<span class="hljs-keyword">time_t</span> startWallTime = system_clock::<span class="hljs-keyword">to_time_t</span>(system_clock::now());
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Time start = "</span> &lt;&lt; <span class="hljs-built_in">std</span>::ctime(&amp;startWallTime) &lt;&lt; <span class="hljs-string">" \n"</span>;
    testFunction();
    <span class="hljs-keyword">auto</span> tEndSteady = <span class="hljs-built_in">std</span>::chrono::steady_clock::now();
    nanoseconds diff = tEndSteady - tStartSteady;
    <span class="hljs-built_in">std</span>::<span class="hljs-keyword">time_t</span> endWallTime = system_clock::<span class="hljs-keyword">to_time_t</span>(system_clock::now());
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Time end = "</span> &lt;&lt; <span class="hljs-built_in">std</span>::ctime(&amp;endWallTime) &lt;&lt; <span class="hljs-string">" \n"</span>;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Time taken = "</span> &lt;&lt; diff.count() &lt;&lt; <span class="hljs-string">" ns"</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>; 
}
</code></pre>
<p>The output of the program is the following:</p>
<pre><code>Output:
<span class="hljs-comment">// This can of course vary from system to system</span>
Time start = Tue Nov  <span class="hljs-number">7</span> <span class="hljs-number">07</span>:<span class="hljs-number">11</span>:<span class="hljs-number">13</span> <span class="hljs-number">2023</span>

Time end = Tue Nov  <span class="hljs-number">7</span> <span class="hljs-number">07</span>:<span class="hljs-number">11</span>:<span class="hljs-number">13</span> <span class="hljs-number">2023</span>

Time taken = <span class="hljs-number">50998885</span> ns
</code></pre><h2 id="heading-summary">Summary</h2>
<p>This article explored various facets of the <code>std::chrono</code> API in C++. The <code>std::chrono</code> API allows C++ programmers to safely keep track of time thanks to its strongly typed system. It also helps maintain support for convenient conversions between different 'types' of time points.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Clang AST-Based C++ Static Analysis Tool ]]>
                </title>
                <description>
                    <![CDATA[ Clang is a set of tools and projects that provides infrastructure for languages in the C family like C, C++, OpenCL, and CUDA. It is a part of the LLVM project. This article will show you how to use Clang's front end libraries to build a simple stati... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/clang-ast-based-static-analysis-tools/</link>
                <guid isPermaLink="false">66b99d5065fc624db0255e07</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jayant Chowdhary ]]>
                </dc:creator>
                <pubDate>Thu, 30 Nov 2023 19:01:21 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/ClangCover-2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Clang is a set of tools and projects that provides infrastructure for languages in the C family like C, C++, OpenCL, and CUDA. It is a part of the <a target="_blank" href="https://www.llvm.org/">LLVM</a> project.</p>
<p>This article will show you how to use Clang's front end libraries to build a simple static analysis tool which will operate on C++ source / header files. It will use the power of AST (Abstract Syntax Tree) traversal. </p>
<p>An abstract syntax tree is a tree structure representing the syntactical structure of code. <a target="_blank" href="https://en.wikipedia.org/wiki/Abstract_syntax_tree">Here</a> is a good explanation of how it works, and <a target="_blank" href="https://astexplorer.net/">here</a> is a tool to help you explore the AST for a given piece of code. </p>
<p>Here, I will teach you how you can use the Clang AST to find information about the code given to it to show you how powerful it is.</p>
<p>This article goes through everything step by step, and I’ll explain the terminology I'm using briefly at each step.</p>
<p>In the first section, you'll learn how to get the open source Clang project. Then, we'll explore how you can build a static analysis tool with a simple goal: to check if each <code>Class</code> defined in a source / header file starts with an uppercase character. We'll do this using Clang's frontend libraries which will analyze the C++ source AST. </p>
<p>So go ahead and grab your favorite coding beverage, get comfortable, and read on!</p>
<p>Here's what we'll cover:</p>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#how-to-get-the-clang-project-and-access-front-end-libraries">How to Get the Clang Project and Access the Front-end Libraries</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-the-scaffolding-for-the-static-analysis-tool">How to Create the Scaffolding for the Static Analysis Tool</a></li>
<li><a class="post-section-overview" href="#heading-putting-it-all-together-in-code">Putting it All Together in Code</a></li>
<li><a class="post-section-overview" href="#heading-summary">Summary</a></li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before getting started, it would be beneficial to have a basic understanding of the following:</p>
<ul>
<li>Compilers: <a target="_blank" href="https://en.wikipedia.org/wiki/Compiler#:~:text=In%20computing%2C%20a%20compiler%20is,language%20(the%20target%20language).">this</a> page is a good primer for beginners.</li>
<li>C++ : For readers not familiar with C++, <a target="_blank" href="https://www.freecodecamp.org/news/learn-c-with-free-31-hour-course/">Learn C++ Programming for Beginners – Free 31-Hour Course</a> is a helpful resource.</li>
<li>Git: <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-git-best-practices-for-beginners/">Git Best Practices – A Guide to Version Control for Beginners</a> is an excellent starting point.</li>
</ul>
<h2 id="heading-how-to-get-the-clang-project-and-access-the-front-end-libraries">How to Get the Clang Project and Access the Front-end Libraries</h2>
<p>Since <code>clang</code> and <code>llvm</code> are open source projects, they have very comprehensive documentation around how to get started with getting the code and building tools using them. </p>
<p>You can check out the <a target="_blank" href="https://llvm.org/docs/GettingStarted.html">Getting Started</a> page of the <code>llvm</code> project to get more information about this. I've referenced that in this article as well.</p>
<p>###1. Get the Clang project </p>
<p>On a UNIX like terminal, clone the <code>llvm</code> Git project into your own directory. I'll call it <code>ast-anaylzer</code>.</p>
<ol>
<li><code>mkdir -p  ~/ast-analyzer; cd ~/ast-analyzer</code></li>
<li><code>git clone https://github.com/llvm/llvm-project.git</code> #Clone the llvm project source </li>
</ol>
<p>###2. Get the CMake build system and Ninja build tool</p>
<p><a target="_blank" href="https://cmake.org/">CMake</a> and <a target="_blank" href="https://ninja-build.org/">ninja</a> work in conjunction to form a build system. <code>CMake</code> generates <code>build.ninja</code> files, which contain commands that tell <code>ninja</code> how to generate output targets. We’ll get into this more a little later.</p>
<p>####2.1 Get and install Ninja</p>
<p>Here are the steps you can follow to install Ninja:</p>
<ol>
<li><code>cd ~/ast-analyzer</code></li>
<li>Clone the ninja source project with this command: <code>git clone https://github.com/martine/ninja.git</code> </li>
<li><code>cd ninja</code></li>
<li>Checkout the release branch - this is the stable branch - with this command: <code>git checkout release</code></li>
<li><code>python3 configure.py –bootstrap</code> This prepares and creates a Ninja binary (<code>configure.py –help</code> will give you more information).</li>
<li>Install ninja with this command: <code>sudo cp ninja /usr/local/bin</code>. After this step, as a basic validity check, do <code>which ninja</code> to make sure it says /usr/local/bin/ninja.</li>
</ol>
<p>####2.2. Get and install CMake</p>
<p>Here are the steps you can follow to install cmake:</p>
<ol>
<li><code>cd ~/ast-analyzer</code></li>
<li>Clone the cmake project source code: <code>git clone git://cmake.org/stage/cmake.git</code></li>
<li><code>cd cmake</code></li>
<li>Checkout the release branch - this is the stable branch - with this command: <code>git checkout release</code>.</li>
<li>Run the bootstrap script: <code>./bootstrap</code>. This prepares cmake to be built and installed on your host machine.</li>
<li>Build cmake from source with this command: <code>make</code>.</li>
<li>Then finally install cmake: <code>sudo make install</code>.</li>
</ol>
<p>Once we’ve gotten Clang, we’ll build it and configure it so we can build Clang-based tools as well.</p>
<p>###3. Build Clang and configure it</p>
<p>Create a ‘build’ directory. This is where our build.ninja/ output binaries and so on will get created:</p>
<pre><code>cd ~/ast-analyzer; mkdir -p build; cd build
</code></pre><p>Now we need to generate the <code>build.ninja file</code> in order to build Clang and also the tools in the directory from the project cloned earlier (<code>llvm/clang-tools-extra</code>). You can do this using <code>CMake</code> like this:</p>
<pre><code>cmake -G Ninja ../llvm-project/llvm -DLLVM_ENABLE_PROJECTS=<span class="hljs-string">"clang;clang-tools-extra"</span> # Enable the clang-tools projects <span class="hljs-keyword">in</span> our build <span class="hljs-keyword">as</span> well
</code></pre><p>This should generate a build.ninja file, which I encourage you to open and check out the contents. You will see that it contains a list of targets followed by dependencies. For example, one of the targets may look something like this: </p>
<pre><code>#############################################
# Utility command <span class="hljs-keyword">for</span> install-llvm-headers

build install-llvm-headers: phony CMakeFiles/install-llvm-headers llvm-headers
</code></pre><p> We’ll also do this for the custom static analysis tool we build in the next steps.</p>
<p>###4. Build and install all targets specified in the build.ninja file</p>
<p><code>ninja; ninja install</code></p>
<p>Okay, the setup is done and now we get to the fun part!</p>
<h2 id="heading-how-to-create-the-scaffolding-for-the-static-analysis-tool">How to Create the Scaffolding for the Static Analysis Tool</h2>
<p>We’ll be building our tool as a part of the <code>clang-tools-extra</code> directory in <code>llvm-project/clang-tools-extra</code>. Let's go ahead and create that directory. We’ll call our tool <code>class-analyzer</code>.</p>
<pre><code>mkdir ~<span class="hljs-regexp">/ast-analyzer/</span>llvm-project/clang-tools-extra/<span class="hljs-class"><span class="hljs-keyword">class</span>-<span class="hljs-title">analyzer</span>
<span class="hljs-title">cd</span> ~/<span class="hljs-title">ast</span>-<span class="hljs-title">analyzer</span>/<span class="hljs-title">llvm</span>-<span class="hljs-title">project</span>/<span class="hljs-title">clang</span>-<span class="hljs-title">tools</span>-<span class="hljs-title">extra</span>/<span class="hljs-title">class</span>-<span class="hljs-title">analyzer</span></span>
</code></pre><p>Now we need to create a <code>CMakeLists.txt</code>. This is basically a file that tells the <code>CMake</code> build system to add the source files in this tool to the <code>build.ninja</code> file it will generate. This lets <code>ninja</code> know how to build our tool.</p>
<p>Our <code>CMakeLists.txt</code> file will look like this:</p>
<p>CMakeLists.txt</p>
<pre><code>set(LLVM_LINK_COMPONENTS support)
set(CMAKE_CXX_COMPILER /usr/bin/clang++)  


add_clang_executable(<span class="hljs-class"><span class="hljs-keyword">class</span>-<span class="hljs-title">analyzer</span>
  <span class="hljs-title">ClassAnalzyer</span>.<span class="hljs-title">cpp</span>
  <span class="hljs-title">MyFrontendActionFactory</span>.<span class="hljs-title">cpp</span>
  <span class="hljs-title">MyFrontendAction</span>.<span class="hljs-title">cpp</span>
  <span class="hljs-title">MyASTConsumer</span>.<span class="hljs-title">cpp</span>
  )
<span class="hljs-title">target_link_libraries</span>(<span class="hljs-title">class</span>-<span class="hljs-title">analyzer</span>
  <span class="hljs-title">PRIVATE</span>
  <span class="hljs-title">clangAST</span>
  <span class="hljs-title">clangFrontend</span>
  <span class="hljs-title">clangTooling</span>
  )</span>
</code></pre><p>The first couple lines tell the build system that the compiler should be <code>/usr/local/bin/clang++</code> (the one just built in the previous steps).</p>
<p>The next <code>add_clang_executable</code> section tells the build system which source files to build as a part of our executable. We'll get more into the details of what each source file does soon. It also tells defines the name of the executable for the build system. Here it is called <code>class-analyzer</code> since it analyzes class names. </p>
<p>The <code>target_link_libraries</code> section informs the build system about the Clang front end libraries we should be linking against. These are the libraries which really expose the power of Clang’s AST to the tool we'll build.</p>
<p>Clang's API documentation is a good place to start looking for hints on how we should start writing the <code>class-analyzer</code> tool. Another good place to start is by scanning the source code of the Clang project we cloned earlier, for other tools! <code>[clang-tools-extra](https://github.com/llvm/llvm-project/tree/main/clang-tools-extra)</code> has multiple examples – these have been a source of inspiration for the code written here.</p>
<p>So now, let's start with the code for our very first source file. This file is contains the <code>main()</code> function of the executable. It looks something like this:</p>
<pre><code class="lang-cpp">
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"clang/Tooling/CommonOptionsParser.h"</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"clang/Tooling/Tooling.h"</span></span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyFrontendActionFactory.h"</span></span>

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

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> clang::tooling;
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> llvm;

<span class="hljs-keyword">static</span> llvm::<span class="hljs-function">cl::OptionCategory <span class="hljs-title">toolCategory</span><span class="hljs-params">(<span class="hljs-string">"class-analyzer &lt;options&gt;"</span>)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">int</span> argc, <span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span>** argv)</span>
</span>{
    <span class="hljs-comment">// Use clang's argument parser infrastructure</span>
    <span class="hljs-comment">// This is used for giving clang tooling the path</span>
    <span class="hljs-comment">// to the source files passed in to the tool.</span>
    <span class="hljs-comment">// It also gets the compilation database - a collection</span>
    <span class="hljs-comment">// of the compiler options used in the invocation of the tool</span>
    <span class="hljs-keyword">auto</span> argsParser = CommonOptionsParser::create(
        argc, argv, toolCategory);
    <span class="hljs-keyword">if</span> (!expectedArgsParser) {
        llvm::errs() &lt;&lt; argsParser.takeError();
        <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;
    }
    CommonOptionsParser&amp; optionsParser
        = argsParser.get();
    <span class="hljs-function">ClangTool <span class="hljs-title">tool</span><span class="hljs-params">(optionsParser.getCompilations(),
                   optionsParser.getSourcePathList())</span></span>;
    <span class="hljs-keyword">auto</span> myActionFactory
        = <span class="hljs-built_in">std</span>::make_unique&lt;MyFrontendActionFactory&gt;();

    <span class="hljs-keyword">return</span> tool.run(myActionFactory.get());
}
</code></pre>
<p>This source file essentially creates a tool which runs a <code>clang</code> <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1tooling_1_1FrontendActionFactory.html"><code>FrontendActionFactory</code></a>. Now to understand what <code>FrontendActionFactory</code> does, let's take a look at Clang's documentation for it. </p>
<p>We see that it has a pure virtual method, </p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;FrontendAction&gt; <span class="hljs-title">create</span> <span class="hljs-params">()</span> </span>= <span class="hljs-number">0</span>;
</code></pre>
<p>which returns an <a target="_blank" href="https://en.cppreference.com/w/cpp/memory/unique_ptr"><code>std::unique_ptr</code></a> to a <code>[FrontendAction](https://clang.llvm.org/doxygen/classclang_1_1FrontendAction.html)</code> object. <code>FrontendAction</code> is, in its essence, a class which allows callers to perform custom actions as Clang parses the AST of a translation unit given to it. A <a target="_blank" href="https://en.wikipedia.org/wiki/Translation_unit_(programming)">translation unit</a> in simple words is the combined code given to the compiler to create an object file. It contains code included through all the header files + code in a C / C++ source file</p>
<p> This will become clearer as we get further along in the article.</p>
<p>Now we come to writing our own <code>FrontendActionFactory</code> which you can call <code>MyFrontendActionFactory</code>. This is a very simple class which just overrides the <code>create()</code> virtual method. It looks like this:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Header file MyFrontendActionFactory.h</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>

include&lt;clang/Tooling/Tooling.h&gt;


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyFrontendActionFactory</span> :</span> <span class="hljs-keyword">public</span> clang::tooling::FrontendActionFactory{
    <span class="hljs-keyword">public</span>:
    MyFrontendActionFactory();
    <span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;clang::FrontendAction&gt; <span class="hljs-title">create</span><span class="hljs-params">()</span> <span class="hljs-keyword">override</span></span>;
};                                                         

<span class="hljs-comment">// Source file MyFrontendActionFactory.cpp</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyFrontendActionFactory.h"</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyFrontendAction.h"</span></span>

MyFrontendActionFactory::MyFrontendActionFactory() {

}

<span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;clang::FrontendAction&gt; <span class="hljs-title">MyFrontendActionFactory::create</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">std</span>::make_unique&lt;MyFrontendAction&gt;();
}
</code></pre>
<p>Since <code>MyFrontendActionFactory::create()</code> needs to return an <code>std::unique_ptr</code> to <code>clang::FrontendAction</code>, we'll need to create a <code>clang::FrontendAction</code> object. </p>
<p>If we look at the Clang documentation for <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1FrontendAction.html"><code>FrontendAction</code></a>, we'll be particularly interested in looking at what we can do with the AST (Abstract Syntax Tree) of the source. </p>
<p>We might spot the following method:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt; ASTConsumer &gt;
<span class="hljs-title">CreateASTConsumer</span> <span class="hljs-params">(CompilerInstance &amp;CI, StringRef InFile)</span> </span>= <span class="hljs-number">0</span>;
</code></pre>
<p>This is a virtual method that a class which inherits from FrontendAction can implement. It returns an <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1ASTConsumer.html#details"><code>ASTConsumer</code></a> which according to the documentation,</p>
<blockquote>
<p> <em>"...is an abstract interface that should be implemented by clients that read ASTs."</em></p>
</blockquote>
<p>So, this method looks really promising if we want to create something that will let us read the Clang generated AST!</p>
<p>If we look at the <code>FrontendAction</code> documentation again, it shows us that <code>ASTFrontend</code> is a class that inherits from <code>FrontendAction</code>. We also learn that it is:</p>
<blockquote>
<p>"The Abstract base class to use for AST consumer-based frontend actions."</p>
</blockquote>
<p>It only has one pure virtual method: <code>CreateASTConsumer()</code>. This seems promising, since...we might be able to create our own <code>ASTConsumer</code> object.</p>
<p>So, we start by reading through <code>ASTConsumer</code>'s <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1ASTConsumer.html">documentation</a>. We see that it has a virtual method</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span>
clang::ASTConsumer::HandleTranslationUnit(ASTContext &amp;Ctx)
</code></pre>
<p>where the documentation states:</p>
<blockquote>
<p> "<code>HandleTranslationUnit</code> - This method is called when the ASTs for entire translation unit have been parsed". </p>
</blockquote>
<p>This is exactly what we want. We can override this method to do interesting things with the parsed AST.</p>
<p>You might now be wondering – how exactly can we use the parameter passed to this function <code>ASTContext</code> to actually go through the AST? </p>
<p>There's a class in the Clang front end API which can help us here: <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1RecursiveASTVisitor.html"><code>RecursiveASTVisitor</code></a>. This is a class that does a depth-first traversal of the Clang AST and visits each node. It has methods such as <code>VisitDecl()</code>, <code>VisitStmt()</code> and so on which can help us go through virtually the whole source file's AST. </p>
<p>It also has a method which is particularly interesting: <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1RecursiveASTVisitor.html#a99a9e941a07a015bc18d3613c5aa0914"><code>TraverseDecl()</code></a>. This method recursively traverses through all the declarations starting from the root declaration given to it.</p>
<h2 id="heading-putting-it-all-together-in-code">Putting it All Together in Code</h2>
<p>So now what we need to do is give <code>TraverseDecl()</code> the root declaration of our translation unit and it will traverse the entirety of it. We can define special 'hooks' which will get called as this traversal happens. One such hook is:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">VisitRecordDecl</span><span class="hljs-params">(<span class="hljs-keyword">const</span> clang::RecordDecl *record)</span></span>;
</code></pre>
<p>This is called each time the <code>RecursiveASTVisitor</code> traverses through a <code>CXXRecordDecl</code> – which is Clang speak for a C++ class. We'll overload this method with our own version to do something interesting: getting the C++ Class' name and seeing if it starts with an upper-case character. </p>
<p>Putting all this together, here's what we get:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// MyFrontendAction.h header file</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>

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

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyFrontendAction</span> :</span> <span class="hljs-keyword">public</span> clang::ASTFrontendAction {
    <span class="hljs-keyword">protected</span>:
        <span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;clang::ASTConsumer&gt; <span class="hljs-title">CreateASTConsumer</span><span class="hljs-params">(clang::CompilerInstance &amp;ci, llvm::StringRef file)</span> <span class="hljs-keyword">override</span></span>;
};    

<span class="hljs-comment">// MyFrontendAction.cpp source file</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyFrontendAction.h"</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyASTConsumer.h"</span></span>

<span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;clang::ASTConsumer&gt; <span class="hljs-title">MyFrontendAction::CreateASTConsumer</span><span class="hljs-params">(clang::CompilerInstance &amp;ci, llvm::StringRef file)</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">std</span>::make_unique&lt;MyASTConsumer&gt;(ci, file);
}
</code></pre>
<pre><code class="lang-cpp">
<span class="hljs-comment">//MyASTConsumer.h header file</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;clang/AST/ASTConsumer.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;clang/Frontend/CompilerInstance.h&gt;</span></span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyASTConsumer</span> :</span> <span class="hljs-keyword">public</span> clang::ASTConsumer {

<span class="hljs-keyword">public</span>:
    MyASTConsumer(clang::CompilerInstance &amp;ci, llvm::StringRef file) {}
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">HandleTranslationUnit</span><span class="hljs-params">(clang::ASTContext &amp;context)</span> <span class="hljs-keyword">override</span></span>;
};

<span class="hljs-comment">// MyASTConsumer.cpp source file</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;clang/AST/RecursiveASTVisitor.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyASTConsumer.h"</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-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">isFirstLetterUpperCase</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span> &amp;str)</span> </span>{
    <span class="hljs-keyword">return</span> str.size() != <span class="hljs-number">0</span> &amp;&amp; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">isupper</span>(str[<span class="hljs-number">0</span>]);
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyASTVisitor</span> :</span> <span class="hljs-keyword">public</span> clang::RecursiveASTVisitor&lt;MyASTVisitor&gt; {
    <span class="hljs-keyword">public</span>:
    <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">VisitCXXRecordDecl</span><span class="hljs-params">(<span class="hljs-keyword">const</span> clang::RecordDecl *record)</span> </span>{
        <span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span> name = record-&gt;getNameAsString();

        <span class="hljs-keyword">if</span> (!isFirstLetterUpperCase(name)) {
            <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Record Decl : "</span> &lt;&lt; name
                      &lt;&lt;<span class="hljs-string">" doesn't start with uppercase! \n"</span>;
        }

        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
    <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">TraverseDecl</span><span class="hljs-params">(clang::Decl *decl)</span>  </span>{
        <span class="hljs-keyword">return</span>
           clang::RecursiveASTVisitor&lt;MyASTVisitor&gt;::TraverseDecl(decl);
    }
};

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">MyASTConsumer::HandleTranslationUnit</span><span class="hljs-params">(clang::ASTContext &amp;ctx)</span> </span>{
    clang::TranslationUnitDecl *tuDecl = ctx.getTranslationUnitDecl();
    MyASTVisitor visitor;
    visitor.TraverseDecl(tuDecl);
}
</code></pre>
<p>Now to build, we just do:</p>
<p><code>cd ~/ast-analyzer/build/;  ninja class-analyzer</code></p>
<p>This builds the <code>class-analyzer</code> executable in the <code>build/bin</code> directory.</p>
<p>Now to test out the analyzer, we create a test.cpp source file:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// test.cpp</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> {</span>
<span class="hljs-keyword">public</span>:
 <span class="hljs-keyword">int</span> a;
};

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">testLower</span> {</span>
<span class="hljs-keyword">public</span>:
 <span class="hljs-keyword">int</span> b;
};

<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">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Run <code>class-analyzer</code> on it:</p>
<pre><code>bin/<span class="hljs-class"><span class="hljs-keyword">class</span>-<span class="hljs-title">analyzer</span> <span class="hljs-title">test</span>.<span class="hljs-title">cpp</span></span>
</code></pre><p>The output of this command is :</p>
<pre><code>Record Decl : testLower doesn<span class="hljs-string">'t start with uppercase!</span>
</code></pre><p>We can use a multitude of such <code>Visit*</code> methods such as <code>VisitEnumDecl</code>, <code>VisitFunctionDecl</code>, <code>VisitVarDecl</code>, and so on to get valuable information about the source file and create our own tools. Just think about any tool which runs and performs actions on code or gives suggestions to the user. </p>
<p>You may think that this seems like a lot of work for a small task. But think about the potential. For example, you could write a tool which automatically gives a user suggestions to improve their code style. Or you could create a tool which analyses C++ code and finds lines of code where there might be security vulnerabilities. </p>
<p>The possibilities are endless. Clang's front-end libraries are extremely powerful and you can build many cool projects and tools with them.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, you learned how to get and use the rich collection of Clang's Front-end libraries to parse a C++ source AST. You can use these libraries to write interesting static code analysis tools. </p>
<p>As this article showed, one of the most important parts of the journey of exploring Clang's libraries is the art of reading the API documentation and applying it to the problems your tools aim to solve. I hope you enjoyed the article! </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Binary Search in C++ – Algorithm Example ]]>
                </title>
                <description>
                    <![CDATA[ The binary search algorithm is a divide and conquer algorithm that you can use to search for and find elements in a sorted array.  The algorithm is fast in searching for elements because it removes half of the array every time the search iteration ha... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/binary-search-in-c-algorithm-example/</link>
                <guid isPermaLink="false">66b0a27603036c3282dfd7c0</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ binary search ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Fri, 17 Mar 2023 16:52:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/binary-search-algorithm-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The binary search algorithm is a divide and conquer algorithm that you can use to search for and find elements in a sorted array. </p>
<p>The algorithm is fast in searching for elements because it removes half of the array every time the search iteration happens. </p>
<p>So instead of searching through the whole array, the algorithm removes half of the array where the element to be searched for can't be found. It does this continuously until the element is found. </p>
<p>In a case where the element to be searched for doesn't exist, it returns a value of -1. If the element exists, then it returns the index of the element. </p>
<p>If the explanations above seem complex, then you should check out this <a target="_blank" href="https://www.freecodecamp.org/news/binary-search-in-java-algorithm-example/#:~:text=How%20Does%20the%20Binary%20Search%20Algorithm%20Work%3F">visual guide on how the binary search algorithm works</a>. </p>
<p>In this article, you'll see an implementation of the binary search algorithm in C++.</p>
<p>Let's get started!</p>
<h2 id="heading-binary-search-algorithm-example-in-c">Binary Search Algorithm Example in C++</h2>
<p>In this section, we'll break down and explain the implementation of binary search in C++.</p>
<p>Here's the code:</p>
<pre><code class="lang-c++"><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">binarySearch</span><span class="hljs-params">(<span class="hljs-keyword">int</span> <span class="hljs-built_in">array</span>[], <span class="hljs-keyword">int</span> low, <span class="hljs-keyword">int</span> high, <span class="hljs-keyword">int</span> number_to_search_for)</span> </span>{

    <span class="hljs-keyword">while</span> (low &lt;= high) {
        <span class="hljs-keyword">int</span> mid = low + (high - low) / <span class="hljs-number">2</span>;

        <span class="hljs-keyword">if</span> (number_to_search_for == <span class="hljs-built_in">array</span>[mid]){
            <span class="hljs-keyword">return</span> mid;
        }

        <span class="hljs-keyword">if</span> (number_to_search_for &gt; <span class="hljs-built_in">array</span>[mid]){
            low = mid + <span class="hljs-number">1</span>;
        }

        <span class="hljs-keyword">if</span> (number_to_search_for &lt; <span class="hljs-built_in">array</span>[mid]){
            high = mid - <span class="hljs-number">1</span>;
        }

    }

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

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">int</span> arrayOfNums[] = {<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">7</span>,<span class="hljs-number">9</span>,<span class="hljs-number">10</span>,<span class="hljs-number">13</span>,<span class="hljs-number">20</span>};

  <span class="hljs-keyword">int</span> n = <span class="hljs-keyword">sizeof</span>(arrayOfNums) / <span class="hljs-keyword">sizeof</span>(arrayOfNums[<span class="hljs-number">0</span>]);

  <span class="hljs-keyword">int</span> result = binarySearch(arrayOfNums, <span class="hljs-number">0</span>, n - <span class="hljs-number">1</span>, <span class="hljs-number">13</span>);

  <span class="hljs-keyword">if</span> (result == <span class="hljs-number">-1</span>){
      <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element doesn't exist in the array"</span>);
  }
  <span class="hljs-keyword">else</span>{
      <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The index of the element is %d"</span>, result);
  }

  <span class="hljs-comment">// The index of the element is 5</span>
}
</code></pre>
<p>To start with, we created a method called <code>binarySearch</code> which had four parameters:</p>
<ul>
<li><code>array[]</code> represents the array to be searched through.</li>
<li><code>low</code> represents the first element of the array. </li>
<li><code>high</code> represents the last element of the array. </li>
<li><code>number_to_search_for</code> represents the number to be searched for in <code>array[]</code>. </li>
</ul>
<p>Next, we created a <code>while</code> loop that will run continuously until the search operation returns a value – either the index of the element or -1. </p>
<p>In the <code>while</code> loop:</p>
<p><code>mid</code> is used to represent the center/midpoint of the array: <code>int mid = low + (high - low) / 2;</code>.</p>
<p>The first <code>if</code> statement is executed if <code>mid</code> has the same value as the element to be searched for: </p>
<pre><code class="lang-c++"><span class="hljs-keyword">if</span> (number_to_search_for == <span class="hljs-built_in">array</span>[mid]){
    <span class="hljs-keyword">return</span> mid;
}
</code></pre>
<p>The second <code>if</code> statement moves the position of <code>low</code> to the index after the midpoint of the array:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">if</span> (number_to_search_for &gt; <span class="hljs-built_in">array</span>[mid]){
    low = mid + <span class="hljs-number">1</span>;
}
</code></pre>
<p>This removes all the elements on the left side of the array because the element to be searched for is greater than they are, so there is no need to search through that part of the array.</p>
<p>The third <code>if</code> statement does the opposite of the second statement – it moves the position of high to the index before the midpoint of the array: </p>
<pre><code class="lang-c++"><span class="hljs-keyword">if</span> (number_to_search_for &lt; <span class="hljs-built_in">array</span>[mid]){
    high = mid - <span class="hljs-number">1</span>;
}
</code></pre>
<p>Here's a summary of the code in the <code>if</code> statements: </p>
<ol>
<li>If the number to be searched for is equal to <code>mid</code>, the <code>mid</code> index will be returned.</li>
<li>If the number to be searched for is greater than <code>mid</code>, search through the elements on the right side of <code>mid</code>.</li>
<li>If the number to be searched for is less than <code>mid</code>, search through the elements on the left side of <code>mid</code>.</li>
</ol>
<p>If the number to be searched for doesn't exist, -1 will be returned. You can see this after the <code>while</code> loop in the code. </p>
<p>Lastly, we tested the <code>binarySearch</code> method:</p>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">int</span> arrayOfNums[] = {<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">7</span>,<span class="hljs-number">9</span>,<span class="hljs-number">10</span>,<span class="hljs-number">13</span>,<span class="hljs-number">20</span>};

  <span class="hljs-keyword">int</span> n = <span class="hljs-keyword">sizeof</span>(arrayOfNums) / <span class="hljs-keyword">sizeof</span>(arrayOfNums[<span class="hljs-number">0</span>]);

  <span class="hljs-keyword">int</span> result = binarySearch(arrayOfNums, <span class="hljs-number">0</span>, n - <span class="hljs-number">1</span>, <span class="hljs-number">13</span>);

  <span class="hljs-keyword">if</span> (result == <span class="hljs-number">-1</span>){
      <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Element doesn't exist in the array"</span>);
  }
  <span class="hljs-keyword">else</span>{
      <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The index of the element is %d"</span>, result);
  }

  <span class="hljs-comment">// The index of the element is 5</span>
}
</code></pre>
<p>In the code above, we passed in the values of the parameters created in the <code>binarySearch</code> method: <code>binarySearch(arrayOfNums, 0, n -1, 13)</code>. </p>
<ul>
<li><code>arrayOfNums</code> represents the array to be searched for: {2,4,7,9,10,13,20}. </li>
<li><code>0</code> represents the first index of the array. </li>
<li><code>n - 1</code> represents the last index of the array. Have a look at the code to see how <code>n</code> was created. </li>
<li><code>13</code> is the number to be searched for in <code>arrayOfNums</code>.</li>
</ul>
<p>When you run the code, "The index of the element is 5" will be printed in the console. This is because the index of the number to be searched for (13) is 5. </p>
<p>You can play around with the code by changing the value of the number to be searched for.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about the implementation of the binary search algorithm in C++. </p>
<p>We saw a code example that had a <code>binarySearch</code> method which took in parameters, searched through an array of numbers, and returned the appropriate value after the search operation. </p>
<p>We also saw a detailed explanation of each part of the code. </p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python VS C++ Time Complexity Analysis ]]>
                </title>
                <description>
                    <![CDATA[ Speed is important in programming languages, and some execute much faster than others. For example, you might know that C++ is faster than Python. So why is this the case? Well, C++ is a language that uses a compiler, not to mention it is a much lowe... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-vs-c-plus-plus-time-complexity-analysis/</link>
                <guid isPermaLink="false">66ba5e22e727ef4561965ab2</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Anthony Behery ]]>
                </dc:creator>
                <pubDate>Wed, 01 Mar 2023 19:07:56 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/aron-visuals-BXOXnQ26B7o-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Speed is important in programming languages, and some execute much faster than others.</p>
<p>For example, you might know that C++ is <strong>faster</strong> than Python. So why is this the case?</p>
<p>Well, C++ is a language that uses a compiler, not to mention it is a much lower-level programming language than Python. That is to say, C++ provides much less <strong>abstraction</strong> from a computer's instruction set and architecture. </p>
<p>On the other hand, Python is an interpretated language, which just means that every line of the program is evaluated as the program is running. </p>
<p>But, how much faster IS C++ compared to Python? In this article you will see 3 algorithms and how they perform in C++ and Python. These algorithms are from "Data Structures and Algorithms Using C++" by Michael T. Goodrich. </p>
<blockquote>
<p><em>Note: The computer I ran these tests on was an Acer Swift 3. The CPU was a Ryzen 7 7500U with Radeon Graphics 1.80Gz. Along with 8GB of RAM, running Windows 10 Home.</em> </p>
</blockquote>
<p>You will be looking at these algorithms and their <strong>Big O Notation</strong>. Big O is a mathematical way of expressing the worst-case scenario of the time or space complexity of an algorithm. </p>
<p>The time complexity is the amount of time it takes for an algorithm to run, while the space complexity is the amount of space (memory) an algorithm takes up. Here is a graph to help explain Big O:</p>
<p><img src="https://paper-attachments.dropbox.com/s_2D428973624E7FC84C7D69D11421DE762BEA6B6F3361231FCDCAE0425D14526F_1664885448372_Untitled.drawio+17.png" alt="Chart" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.freecodecamp.org/news/big-o-cheat-sheet-time-complexity-chart/">Big O Cheat Sheet – Time Complexity Chart (freecodecamp.org)</a></em></p>
<p>From now on, I'll refer to each algorithm as running with a certain time complexity. </p>
<p>For example, if I say an algorithm runs with a <strong>O(n)</strong> time complexity, this means that as the input grows, the time it takes for an algorithm to run is <strong>linear</strong>. If I say it runs with <strong>O(n^2)</strong> time complexity, this means that as the input grows, the time it takes for an algorithm to run is <strong>quadratic</strong>. </p>
<h3 id="heading-performance-of-the-1st-algorithm">Performance of the 1st Algorithm:</h3>
<pre><code>Algorithm Ex1(A):
    Input: An array <span class="hljs-string">"A"</span> storing n &gt;= <span class="hljs-number">1</span> integers.
    Output: The sum <span class="hljs-keyword">of</span> the elements <span class="hljs-keyword">in</span> A.

    s = A[<span class="hljs-number">0</span>]
    <span class="hljs-keyword">for</span> i = <span class="hljs-number">1</span> to n - <span class="hljs-number">1</span> <span class="hljs-keyword">do</span>:
        s = s + A[i]
    <span class="hljs-keyword">return</span> s
</code></pre><p>In Python, we can express this algorithm as:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">ex1</span>(<span class="hljs-params">A</span>):</span>
    sum = A[<span class="hljs-number">0</span>]
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> A:
        sum = sum + A[i]
    <span class="hljs-keyword">return</span> sum
</code></pre>
<p>If you use inputs up to about 5 million you will see that this algorithm takes about 4 seconds to run with that large of an input. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-228.png" alt="Image" width="600" height="400" loading="lazy">
<em>Performance of the 1st Algorithm</em></p>
<p>Then you can compare this algorithm in C++, like this:</p>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">ex1</span><span class="hljs-params">(<span class="hljs-keyword">double</span> A[], <span class="hljs-keyword">size_t</span> n)</span>
</span>{
    <span class="hljs-keyword">double</span> sum = A[<span class="hljs-number">0</span>];
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">size_t</span> i = <span class="hljs-number">0</span>; i &lt; n; i++)
    {
        s = s + A[i];
    }
    <span class="hljs-keyword">return</span> sum;
}
</code></pre>
<p>You may be wondering, what is <code>size_t</code>? <code>size_t</code> is an "unsigned integer". This just means that this variable does not have a sign. Which also just means that this variable is <strong>not negative</strong>. </p>
<p>In C++, we use <code>size_t</code> to keep track of positions in an array, since those positions cannot be negative (at least in C++, since in Python we can have negative indexes).</p>
<p>Now let's take a look at the running time of the first algorithm:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-230.png" alt="Image" width="600" height="400" loading="lazy">
<em>Performance of the 1st Algorithm in C++</em></p>
<p>As you can see from these two charts, the time complexity seems to be linear. This means that the time complexity of this algorithm is <strong>O(n)</strong> – as the input size for <code>A</code> grows, the time it takes for this algorithm to run grows <strong>linearly.</strong></p>
<p>But it is interesting to notice that for very large inputs of 5 million, C++ does not even break the 1 second mark. Whereas Python breaks the 3-4 second mark for inputs at about 5 million. Let's move on to our next algorithm.</p>
<h3 id="heading-performance-of-the-2nd-algorithm">Performance of the 2nd Algorithm:</h3>
<pre><code>Algorithm Ex3(A):
    Input: An array <span class="hljs-string">"A"</span> storing n &gt;= <span class="hljs-number">1</span> integers.
    Output: The sum <span class="hljs-keyword">of</span> the prefix sums <span class="hljs-keyword">in</span> A.
    s = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i = <span class="hljs-number">0</span> to n - <span class="hljs-number">1</span> <span class="hljs-keyword">do</span>:
        s = s + A[<span class="hljs-number">0</span>]
        <span class="hljs-keyword">for</span> j = <span class="hljs-number">1</span> to i <span class="hljs-keyword">do</span>:
            s = s + A[j]
    <span class="hljs-keyword">return</span> s
</code></pre><p>Here, you can see that this algorithm has two for-loops. So, moving forward this is something to acknowledge when analyzing the time complexity. </p>
<p>In Python, you can express this algorithm like this:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">ex3</span>(<span class="hljs-params">A</span>):</span>
    sum = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(A)):
        sum = sum + A[i]
        <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, i):
            sum = sum + A[j]
    <span class="hljs-keyword">return</span> sum
</code></pre>
<p>Let's also use inputs all the way up to 70,000. Then we will record the times and chart the data like so:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-235.png" alt="Image" width="600" height="400" loading="lazy">
<em>Time Performance of the 2nd Algorithm in Python</em></p>
<p>These results are much different from our previous charts from algorithm 1. Something to point out is that with an input of 70,000, this algorithm takes a whopping 91 seconds in Python. Thats a long time! </p>
<p>Also, when I tried to run inputs higher than 70,000, my computer started to become unresponsive. Yikes.</p>
<p>Let's take a look at this algorithm in C++:</p>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">ex3</span><span class="hljs-params">(<span class="hljs-keyword">double</span> A[], <span class="hljs-keyword">size_t</span> n)</span>
</span>{
    <span class="hljs-keyword">double</span> s = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">size_t</span> i = <span class="hljs-number">0</span>; i &lt; n; i++)
    {
        s = s + A[i];
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">size_t</span> j = <span class="hljs-number">1</span>; j &lt; i; j++)
        {
            s = s + A[j];
        }
    }
    <span class="hljs-keyword">return</span> s;
}
</code></pre>
<p>For the C++ code I was able to increase the input size to ~90,000.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-238.png" alt="Image" width="600" height="400" loading="lazy">
<em>Time Performance of the 2nd Algorithm in C++</em></p>
<p>For an input size of 70,000 this algorithm takes ~4 seconds to run in C++. That difference is huge. Not to mention, I was able to use inputs that were about ~90,000 elements in size for C++, with it not even breaking past the 10 second mark. </p>
<p>Also, we can see that the curve is not as smooth as the Python graph. This could be due to some other processes running in the background (since I'm running on Windows 10) or some other reason. </p>
<p>Also, we can classify the time complexity of this algorithm as <strong>O(n^2)</strong>, which just means that the time complexity for this algorithm is quadratic. </p>
<p>Let's move on to the last algorithm.</p>
<h3 id="heading-performance-of-the-3rd-algorithm">Performance of the 3rd Algorithm:</h3>
<pre><code>Algorithm Ex5(A, B):
    Input: Arrays <span class="hljs-string">"A"</span> and <span class="hljs-string">"B"</span> each storing n &gt;= <span class="hljs-number">1</span> integers.
    Output: The number <span class="hljs-keyword">of</span> elements <span class="hljs-keyword">in</span> B equal to the sum <span class="hljs-keyword">of</span>
            prefix sums <span class="hljs-keyword">in</span> A.
    c = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i = <span class="hljs-number">0</span> to n - <span class="hljs-number">1</span> <span class="hljs-keyword">do</span>:
        s = <span class="hljs-number">0</span>
        <span class="hljs-keyword">for</span> j = <span class="hljs-number">0</span> to n - <span class="hljs-number">1</span> <span class="hljs-keyword">do</span>:
            s = s + A[<span class="hljs-number">0</span>]
            <span class="hljs-keyword">for</span> k = <span class="hljs-number">1</span> to j <span class="hljs-keyword">do</span>:
                s = s + A[k]
            <span class="hljs-keyword">if</span> B[i] == s then:
                c = c + <span class="hljs-number">1</span>
    <span class="hljs-keyword">return</span> c
</code></pre><p>Let's take a look at this code in Python:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">ex3</span>(<span class="hljs-params">A, B</span>):</span>
    c = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(A)):
        s = <span class="hljs-number">0</span>
        <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(len(A)):
            s = s + A[<span class="hljs-number">0</span>]
            <span class="hljs-keyword">for</span> k <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, j):
                s = s + A[k]
            <span class="hljs-keyword">if</span> B[i] == s:
                c = c + <span class="hljs-number">1</span>
    <span class="hljs-keyword">return</span> c
</code></pre>
<p>Now, let's analyze the timings:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-241.png" alt="Image" width="600" height="400" loading="lazy">
<em>Time Performance of the 3rd Algorithm in Python</em></p>
<p>Woah, what's going on here? We can see that as our inputs starts to increase, the rate at which the algorithm runs also starts to increase, but it is increasing at a drastic rate. </p>
<p>In this case, we can see with an input size of 3500 that it takes 761 seconds for this algorithm to run in Python. You may be asking, "Did you actually sit through all 761 seconds?", the answer is yes. Yes, I did. </p>
<p>Now let's take a look at the C++ code:</p>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">ex5</span><span class="hljs-params">(<span class="hljs-keyword">double</span> A[], <span class="hljs-keyword">double</span> B[], <span class="hljs-keyword">size_t</span> n)</span>
</span>{
    <span class="hljs-keyword">double</span> c = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">size_t</span> i = <span class="hljs-number">0</span>; i &lt; n; i++)
    {
        <span class="hljs-keyword">double</span> s = <span class="hljs-number">0</span>;
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">size_t</span> j = <span class="hljs-number">0</span>; j &lt; n; i++)
        {
            s = s + A[<span class="hljs-number">0</span>]
            <span class="hljs-keyword">for</span>(<span class="hljs-keyword">size_t</span> k = <span class="hljs-number">1</span>; k &lt; j; k++)
            {
                s = s + A[k];
            }
            <span class="hljs-keyword">if</span>(B[i] == s)
            {
                c = c + <span class="hljs-number">1</span>
            }
        }
    }
    <span class="hljs-keyword">return</span> c;
}
</code></pre>
<p>Let's take a look at the graph.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-243.png" alt="Image" width="600" height="400" loading="lazy">
<em>Time Performance of the 3rd Algorithm in C++</em></p>
<p>Similar to the second algorithm, it is interesting to see that the curve is not as smooth as the Python graph. </p>
<p>Also, we can see that we can go well above an input size of 3500. My computer started acting up once I pushed the input size past 10,000 for C++. Not to mention, with an input size of 10,000 the algorithm averaged about 544-545 seconds. </p>
<p>We can classify this algorithm as having a time complexity of <strong>O(n!).</strong> Which just means that this algorithm is factorial, which runs <strong>very slowly.</strong> </p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>I hope you found the differences of running times between Python and C++ just as fascinating as I have. </p>
<p>Also, just because Python runs slower than C++ for every algorithm does not mean that C++ is the "better" language. Both of these languages have their own purposes for the type of software you are trying to create. </p>
<p>C++ would be the preferred language if performance is critical. If you were programming games, operating systems, or communicating between machinery, C++ would be the better choice due to its compiled and fast nature.</p>
<p>Python would be preferred if you need to develop software quickly. Due to its easier learning curve, almost anyone can pick up Python and start creating software with it. Python also provides many resources for data science and machine learning.</p>
<p>Check out the code if you would like to try these tests on your own computer:</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="a1b590ceea0cb21fb01dfc7013b3a1da">
        <script src="https://gist.github.com/tarmacjupiter/a1b590ceea0cb21fb01dfc7013b3a1da.js"></script></div><div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="4120e8afb57db0559174b3caadbf426d">
        <script src="https://gist.github.com/tarmacjupiter/4120e8afb57db0559174b3caadbf426d.js"></script></div><p>Cheers!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Virtual Inheritance? ]]>
                </title>
                <description>
                    <![CDATA[ C++ supports the concept of inheritance – that is, a class can inherit properties from other classes.  But sometimes you might need to use what is commonly referred as virtual inheritance.  In this article we will discuss when you might need to use v... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-virtual-inheritance/</link>
                <guid isPermaLink="false">66baef9166a27aea1d2a4019</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ inheritance ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Abhilekh gautam ]]>
                </dc:creator>
                <pubDate>Thu, 23 Feb 2023 21:09:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/pexels-ruiyang-zhang-3717242.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>C++ supports the concept of inheritance – that is, a class can inherit properties from other classes. </p>
<p>But sometimes you might need to use what is commonly referred as virtual inheritance. </p>
<p>In this article we will discuss when you might need to use virtual inheritance and how to implement it in C++.</p>
<h2 id="heading-what-is-virtual-inheritance">What is Virtual Inheritance?</h2>
<p>In C++, a class can inherit from multiple classes which is commonly referred as multiple inheritance. But this can cause problems sometimes, as you can have multiple instances of the base class.</p>
<p>To tackle this problem, C++ uses a technique which ensures only one instance of a base class is present. That technique is referred as virtual inheritance.</p>
<h3 id="heading-example-of-when-virtual-inheritance-is-useful">Example of When Virtual Inheritance is Useful</h3>
<p>Let's look at an example and then explain what's happening:</p>
<pre><code class="lang-c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> {</span>
    <span class="hljs-keyword">public</span>:
     <span class="hljs-keyword">int</span> x = <span class="hljs-number">5</span>;
     <span class="hljs-comment">//some other things</span>
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> :</span> <span class="hljs-keyword">public</span> A { <span class="hljs-comment">// inherit from the Class A.</span>
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">6</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span> :</span> <span class="hljs-keyword">public</span> A { <span class="hljs-comment">// inherit from the Class A.</span>
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">7</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">D</span> :</span> <span class="hljs-keyword">public</span> B, <span class="hljs-keyword">public</span> C { <span class="hljs-comment">// inherit from both class B and C</span>
    <span class="hljs-comment">// something can go here..</span>
};

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    D obj;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; obj.x &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Let's see what's going on here:</p>
<p>First, we have a class <code>A</code> which is being inherited by two classes <code>B</code> and <code>C</code>.  Both of these classes are then inherited by another class <code>D</code>. </p>
<p>Inside our <code>main</code> function, we create a new instance (object) of the class <code>D</code>. We then simply tried to print the value of <code>x</code> to the console. </p>
<p>It might look legit to access the value of <code>x</code> here, because class <code>D</code> is inherited from both <code>B</code> and <code>C</code> which are ultimately inherited from the class <code>A</code>. </p>
<p>But when you try to compile the above program, you get the following error:</p>
<pre><code>&lt;source&gt;: In <span class="hljs-function"><span class="hljs-keyword">function</span> '<span class="hljs-title">int</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>)':
&lt;<span class="hljs-title">source</span>&gt;:21:22: <span class="hljs-title">error</span>: <span class="hljs-title">request</span> <span class="hljs-title">for</span> <span class="hljs-title">member</span> '<span class="hljs-title">x</span>' <span class="hljs-title">is</span> <span class="hljs-title">ambiguous</span>
   21 |     <span class="hljs-title">std</span>::<span class="hljs-title">cout</span> &lt;&lt; <span class="hljs-title">obj</span>.<span class="hljs-title">x</span> &lt;&lt; <span class="hljs-title">std</span>::<span class="hljs-title">endl</span>;
      |                      ^
&lt;<span class="hljs-title">source</span>&gt;:5:10: <span class="hljs-title">note</span>: <span class="hljs-title">candidates</span> <span class="hljs-title">are</span>: '<span class="hljs-title">int</span> <span class="hljs-title">A</span>::<span class="hljs-title">x</span>'
    5 |      <span class="hljs-title">int</span> <span class="hljs-title">x</span> = 5;
      |          ^
&lt;<span class="hljs-title">source</span>&gt;:5:10: <span class="hljs-title">note</span>:                 '<span class="hljs-title">int</span> <span class="hljs-title">A</span>::<span class="hljs-title">x</span>'</span>
</code></pre><p>The error is pretty clear: <strong><code>error:</code></strong> <code>request for member '</code><strong><code>x</code></strong><code>' is ambiguous</code>. Let's now see how the request is ambiguous. </p>
<p>If we draw the hierarchical class structure, it should become pretty clear:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/hierarchial-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Hierarchical class structure</em></p>
<p>We can see that we have multiple instances of the class <code>A</code>. So the request to the variable <code>x</code> becomes ambiguous because the compiler doesn't know which instance we are referring to – is it through <code>B</code> or through <code>C</code> ? That's the real problem. </p>
<h3 id="heading-one-way-to-solve-this-problem">One Way to Solve this Problem</h3>
<p>One way to tackle the problem is to use the <code>scope-resolution operator (::)</code> with which we can directly specify which instance of <code>A</code> we want.</p>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    D obj;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; obj.B::x &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; obj.C::x &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
}
</code></pre>
<p>Using the  <code>scope-resolution operator</code> we explicitly told the compiler which instance of <code>A</code> we referred to.</p>
<p>The main problem with this approach is that it doesn't solve our problem – because our main problem is having multiple instances of class <code>A</code>, and we still have that. So we need to look around for some other solutions.</p>
<p>And the other solution is to use virtual inheritance. Let's see how it works now.</p>
<h3 id="heading-how-to-use-virtual-inheritance">How to Use Virtual Inheritance</h3>
<p>To inherit virtually we simply add a keyword <code>virtual</code> before our base class name in the derived class declaration like this:</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> :</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">public</span> A{
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">6</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span> :</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">public</span> A{
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">7</span>;
};
</code></pre>
<p>The addition of the <code>virtual</code> keyword indicates that we want to inherit from <code>A</code> virtually. </p>
<p>Inheriting virtually guarantees that there will be only one instance of the base class among the derived classes that virtually inherited it. After the changes, our hierarchical class structure becomes:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/diamond-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Hierarchical structure after virtual inheritance</em></p>
<p>So now if we try to compile the following code, it will successfully compile.</p>
<pre><code class="lang-c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> {</span>
    <span class="hljs-keyword">public</span>:
     <span class="hljs-keyword">int</span> x = <span class="hljs-number">5</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> :</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">public</span> A{
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">6</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span> :</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">public</span> A{
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">7</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">D</span> :</span> <span class="hljs-keyword">public</span> B, <span class="hljs-keyword">public</span> C{

};

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    D obj;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; obj.x &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

}
</code></pre>
<p>So with the introduction of <code>virtual</code> inheritance we are able to remove the ambiguities we had earlier.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this article you learnt about the problem you might face while inheriting a class and a way to solve it using <code>virtual</code> inheritance.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Print Array Elements in a Given Order with or without a Function ]]>
                </title>
                <description>
                    <![CDATA[ If you are learning to solve problems using a programming language, you've likely faced the problem of printing array elements in a given order or in reverse order. You might have also needed to do this by either using a user-defined function or not ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-print-array-elements-in-given-order-with-and-without-function/</link>
                <guid isPermaLink="false">66b902f7380c84d101de5dac</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Problem Solving ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Md. Fahim Bin Amin ]]>
                </dc:creator>
                <pubDate>Thu, 16 Feb 2023 21:58:53 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/func.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you are learning to solve problems using a programming language, you've likely faced the problem of printing array elements in a given order or in reverse order.</p>
<p>You might have also needed to do this by either using a user-defined function or not using any function at all.</p>
<p>If this problem seems kind of complicated to you, then don't worry! I have come to help you. So, let's dive into the question real quick and see how it works.</p>
<p>🎥 If you are the kind of person that loves to follow along with a video too, I have also created a video for you:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/pACJ2_bGaZ0" 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>
<h2 id="heading-understand-the-question-then-start-solving">Understand The Question – Then Start Solving</h2>
<p>For solving any kind of problem, the first thing you have to do is to understand the question first. Not only that, you also need to pay close attention to all the instructions including the required criteria for solving that problem.</p>
<p>If your question asks you to use recursion, that's the technique you'll employ. If your question asks you not to use any built-in special functions, you'll avoid those.</p>
<p>For this article, I will be using only one question but with two different criteria. I will go through the process to help you understand what you would need to do from the beginning for solving the problem.</p>
<h3 id="heading-heres-the-question-with-its-criteria">Here's the question with its criteria:</h3>
<p>Create an integer array. Take the array elements as input from the user and print all the array elements in the given order and later in reverse order. You can't use any user-defined function.</p>
<p>Alright, now that we have our question, make sure you've read it fully. If reading it through one time does not make it clear in your mind, then read it two or three – or even more – times.</p>
<p>Then also look into the given criteria carefully. The question tells you that you can not use any user defined function. That means you can not add any kind of manually user-defined function in your code like <code>myFunction()</code>, and so on.</p>
<p>For this article, I will be using the <strong>C++</strong> programming language. But if you can understand the core concept then you can use any other programming language to solve this problem. After solving the problem, make sure to add your solution <a target="_blank" href="https://github.com/FahimFBA/problem-solving-made-easy">to this GitHub repository</a>. </p>
<p>Also, if you like to solve problems using programming languages, then make sure to check <a target="_blank" href="https://www.youtube.com/playlist?list=PL7ZCWbO2Dbl5p3wf0IOHeIZ6PHxTI3ADD">my ongoing YouTube playlist where I solve problems using the programming language</a>.</p>
<h3 id="heading-how-to-solve-the-problem">How to Solve the Problem</h3>
<p>In C/C++, if you declare an array without initializing the value, then you need to specify the array size as well. </p>
<p>When you declare the array with the array size, it automatically takes the necessary space in the memory for the entire array. So, if you take a larger array than you actually need, you will waste memory, as it takes the full space in memory for the full array whether you use all the indexes or not. </p>
<p>So first, we want the user to input the array size (how many numbers they want us to process). Then we will create the array with the given array size. In that way, we can save unnecessary memory wastage. </p>
<p>Well, as today's computers are more powerful, you would likely not notice any differences in memory wastage, as it would be pretty negligible. But trust me, you do need to understand how to save memory as that is one of the biggest concerns in today's world. Also, you never know when this knowledge will help you later, right?</p>
<pre><code class="lang-cpp">    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Enter the array size: "</span>;
    <span class="hljs-keyword">int</span> arraySize;
    <span class="hljs-built_in">cin</span> &gt;&gt; arraySize;
    <span class="hljs-keyword">int</span> arr[arraySize];
</code></pre>
<p>Well then, after declaring our array, we will take the array elements from the user. We can simply use a <code>for()</code> loop for that. </p>
<pre><code class="lang-cpp">    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Enter the array elements "</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; arraySize; i++)
    {
        <span class="hljs-built_in">cin</span> &gt;&gt; arr[i];
    }
</code></pre>
<p>In this way, we can take each value from the user and store it in our array in a sequential way. Keep in mind that the array always starts from the <code>0</code> index (the first element is at index <code>0</code>, the second is at index <code>1</code>, and so on).</p>
<p>Now it is time to print all the array elements (the value that each index of the array has) in the given order. That means we have to print the entire array in the same order we received from the user.</p>
<pre><code class="lang-cpp">    <span class="hljs-comment">// printing the array in the correct order</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Printing the array in the original order"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; arraySize; i++)
    {
        <span class="hljs-built_in">cout</span> &lt;&lt; arr[i] &lt;&lt; <span class="hljs-string">" "</span>;
    }
</code></pre>
<p>For printing the array in reverse order, we can simply print the array in a backwards direction. In this way, the last indexed value from the array will get printed first. Then the second to last indexed value (from the right side of the array) would get printed in the second position, and so on.</p>
<pre><code class="lang-cpp">    <span class="hljs-comment">// printing the array in the reverse order</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"\nPrinting the array in the reversed order"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = arraySize - <span class="hljs-number">1</span>; i &gt;= <span class="hljs-number">0</span>; i--)
    {
        <span class="hljs-built_in">cout</span> &lt;&lt; arr[i] &lt;&lt; <span class="hljs-string">" "</span>;
    }
</code></pre>
<p>That's it! Through this, you can solve the problem easily. Notice that we did not use any kind of user-defined function in our entire code. Thus, we also made sure that we successfully met all of the criteria.</p>
<p>The entire code now looks like this:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;bits/stdc++.h&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">cout</span> &lt;&lt; <span class="hljs-string">"Enter the array size: "</span>;
    <span class="hljs-keyword">int</span> arraySize;
    <span class="hljs-built_in">cin</span> &gt;&gt; arraySize;
    <span class="hljs-keyword">int</span> arr[arraySize];
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Enter the array elements "</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; arraySize; i++)
    {
        <span class="hljs-built_in">cin</span> &gt;&gt; arr[i];
    }
    <span class="hljs-comment">// printing the array in the correct order</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Printing the array in the original order"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; arraySize; i++)
    {
        <span class="hljs-built_in">cout</span> &lt;&lt; arr[i] &lt;&lt; <span class="hljs-string">" "</span>;
    }
    <span class="hljs-comment">// printing the array in the reverse order</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"\nPrinting the array in the reversed order"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = arraySize - <span class="hljs-number">1</span>; i &gt;= <span class="hljs-number">0</span>; i--)
    {
        <span class="hljs-built_in">cout</span> &lt;&lt; arr[i] &lt;&lt; <span class="hljs-string">" "</span>;
    }    
}
</code></pre>
<h3 id="heading-heres-another-example-question-and-criteria">Here's another example question and criteria:</h3>
<p>Create an integer array. Take the array elements as input from the user and print all the array elements in the given order and later in the reverse order. You have to use a user-defined function for printing the array in reverse order.</p>
<p>Now, this time the criteria has been changed. The only difference is that we need to use a user defined function right now.</p>
<p>If you can understand the previous technique and the code, then most probably you have already guessed how to solve this problem. We have to shift the part of the code that prints the array in the reverse order to a new user-defined function. Simply doing that will solve our problem. </p>
<p>For example, I am going to name the new user-defined function <code>printReversely(int arr[], int arraySize)</code>. You can name it however you want by following the naming conventions of C++ (or whatever programming language you're using).</p>
<p>I am simply giving you the entire code for now:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;bits/stdc++.h&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">void</span> <span class="hljs-title">printReversely</span><span class="hljs-params">(<span class="hljs-keyword">int</span> arr[], <span class="hljs-keyword">int</span> arraySize)</span></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">cout</span> &lt;&lt; <span class="hljs-string">"Enter the array size: "</span>;
    <span class="hljs-keyword">int</span> arraySize;
    <span class="hljs-built_in">cin</span> &gt;&gt; arraySize;
    <span class="hljs-keyword">int</span> arr[arraySize];
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Enter the array elements "</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; arraySize; i++)
    {
        <span class="hljs-built_in">cin</span> &gt;&gt; arr[i];
    }
    <span class="hljs-comment">// printing the array in the correct order</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Printing the array in the original order"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; arraySize; i++)
    {
        <span class="hljs-built_in">cout</span> &lt;&lt; arr[i] &lt;&lt; <span class="hljs-string">" "</span>;
    }
    <span class="hljs-comment">// printing the array in the reverse order</span>
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"\nPrinting the array in the reversed order"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
    printReversely(arr, arraySize);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">printReversely</span><span class="hljs-params">(<span class="hljs-keyword">int</span> arr[], <span class="hljs-keyword">int</span> arraySize)</span>
</span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = arraySize - <span class="hljs-number">1</span>; i &gt;= <span class="hljs-number">0</span>; i--)
    {
        <span class="hljs-built_in">cout</span> &lt;&lt; arr[i] &lt;&lt; <span class="hljs-string">" "</span>;
    }
}
</code></pre>
<p>In C/C++, the code execution always starts from the upper left corner.</p>
<p>As I wrote my <code>printReversely(int arr[], int arraySize)</code> function after the main function, I added the declaration part of it before the <strong>main()</strong> function. This will help the compiler determine whether it has access to the function or not. If you do not do that, then you'll get an error.</p>
<p>But if you write the entire <code>printReversely(int arr[], int arraySize)</code> function before the <strong>main()</strong> function then you do not necessarily need to add the declaration again before that. </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Thanks for reading the entire article. If it helps you then you can also check out other articles of mine at <a target="_blank" href="https://www.freecodecamp.org/news/author/fahimbinamin/">freeCodeCamp</a>.</p>
<p>If you want to get in touch with me, then you can do so using <a target="_blank" href="https://twitter.com/Fahim_FBA">Twitter</a>, <a target="_blank" href="https://www.linkedin.com/in/fahimfba/">LinkedIn</a>, and <a target="_blank" href="https://github.com/FahimFBA">GitHub</a>. </p>
<p>You can also <a target="_blank" href="https://www.youtube.com/@FahimAmin?sub_confirmation=1">SUBSCRIBE to my YouTube channel</a> (Code With FahimFBA) if you want to learn various kinds of programming languages with a lot of practical examples regularly.</p>
<p>If you want to check out my highlights, then you can do so at my <a target="_blank" href="https://www.polywork.com/fahimbinamin">Polywork timeline</a>.</p>
<p>You can also <a target="_blank" href="https://fahimbinamin.com/">visit my website</a> to learn more about me and what I'm working on.</p>
<p>Thanks a bunch!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Write And Run C and C++ Code in Visual Studio Code ]]>
                </title>
                <description>
                    <![CDATA[ Visual Studio Code (or VS Code for short) is a very common and widely used text editor and IDE (Integrated Development Environment). You can make VS Code very powerful like an IDE using a lot of extensions. Before approaching the process of running y... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-write-and-run-c-cpp-code-on-visual-studio-code/</link>
                <guid isPermaLink="false">66b9030605ed142b6e64c273</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ c programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Visual Studio Code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Visual Studio Code ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Md. Fahim Bin Amin ]]>
                </dc:creator>
                <pubDate>Fri, 20 Jan 2023 21:45:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/asd.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Visual Studio Code (or VS Code for short) is a very common and widely used text editor and IDE (Integrated Development Environment). You can make VS Code very powerful like an IDE using a lot of extensions.</p>
<p>Before approaching the process of running your first C or C++ code on Visual Studio Code, let me guide you through the process and get it all set up based on the operating system you are using on your computer.</p>
<h2 id="heading-c-and-c-compilers">C and C++ compilers</h2>
<p>For running C or C++ code, you just need to have a valid C/C++ compiler installed on your computer. If you are using a Linux operating system, then there is a high chance that it is already installed on your system. But we need to make sure that it is correctly installed.</p>
<p>For checking whether or not you have the compiler (GCC/G++/MinGW) installed on your system or not, you have to check the compiler version first. </p>
<p>Simply open your terminal and use <code>gcc --version</code> and <code>g++ --version</code>. If you get the version number, then the compiler is already installed on your system. </p>
<p>You can check the version using the same commands on any operating system, whether that is a Windows, Linux, or macOS-based operating system. </p>
<p>If you get feedback on your terminal that it does not know anything about GCC or G++, then you have to install the compiler correctly. </p>
<p>If you are using the most used Windows operating system, then I already have written an in-depth article showing you all the processes step-by-step on freeCodeCamp. Make sure to read the entire article first, as it also contains a complete video to provide you with complete support.</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/how-to-install-c-and-cpp-compiler-on-windows/">Embedded content</a></p>
<p>If you are using another operating system, and you don't have the compilers installed, then make sure to install them before proceeding.</p>
<h2 id="heading-how-to-install-vs-code-or-vs-code-insiders">How to Install VS Code or VS Code Insiders</h2>
<p>You have to download Visual Studio Code directly from the official website: <a target="_blank" href="https://code.visualstudio.com/">https://code.visualstudio.com/</a>.</p>
<p>If you want, you can also install VS Code Insiders, and the same process is applicable for that as well. </p>
<p>Visual Studio Code Insiders is actually the "Insiders" build of Visual Studio Code, which contains all the latest features that are shipped daily. You can think of VS Code as the stable release and the VS Code Insiders as the Insiders release of that.</p>
<p>If you want to experience the latest updates instantly, then you might also try Visual Studio Code Insiders (I use it myself). For downloading VS Code Insiders, you can visit the official website for VS Code Insiders here: <a target="_blank" href="https://code.visualstudio.com/insiders/">https://code.visualstudio.com/insiders/</a></p>
<p>Make sure to download the exact file for your operating system.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-163.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Download Page: VS Code</strong></em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-164.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Download Page: VS Code Insiders</strong></em></p>
<p>The installation process is pretty basic. But I am going to show you all the steps sequentially. For now, I am going to show you the installation process using VS Code Insiders, but everything you will see here is going to be exactly the same for VS Code as well.</p>
<p>Make sure to click the box on the "I accept the agreement " box and click on <strong>Next</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-165.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Accept the agreement and click Next</strong></em></p>
<p>Keep everything as it is. Do not change anything from here.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-168.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Click Next</strong></em></p>
<p> Click <strong>Next</strong>. Again, simply click <strong>Next</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-170.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Click Next</strong></em></p>
<p>Make sure to add the checkmark (✔) on all of the boxes. Then click on <strong>Next</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-171.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Check all of the boxes, and click Next</strong></em></p>
<p>Click on <strong>Install</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-172.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Click Install</strong></em></p>
<p>It might take a little time to finish the installation.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-173.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Let it finish...</strong></em></p>
<p>Click on <strong>Finish</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-175.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Click Finish</strong></em></p>
<p>Congrats - you've successfully installed VS Code/VS Code Insiders on your system. Now, cheers! 🥂</p>
<h2 id="heading-how-to-prepare-vs-codevs-code-insiders-for-c-and-c-code">How to Prepare VS Code/VS Code Insiders For C and C++ Code</h2>
<p>First, open VS Code or VS Code Insiders.</p>
<p>Go to the Extension tab. Search for "C" or "C++" and install the first one that is already verified by Microsoft itself.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-178.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Install C/C++ extension</strong></em></p>
<p>Also, install <strong>C/C++ Extension Pack</strong>. It should also be verified by Microsoft.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-179.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Install C/C++ Extension Pack</strong></em></p>
<p>Then you have to search for <strong>Code Runner</strong> and install the extension as well.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-180.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Install Code Runner Extension</strong></em></p>
<p>Now, we need to change some settings.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-177.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Change some settings</strong></em></p>
<p>Click the <strong>gear</strong> box (It is called the Manage section), and then click <strong>Settings</strong>. Alternatively, you can also use the shortcut keys <code>Ctrl</code> + <code>,</code>. You need to replace the <code>Ctrl</code> key with the Command key for Mac.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-182.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Type "Run code in terminal" and press Enter key</strong></em></p>
<p>In the search bar, type "Run code in terminal" and press the Enter key.</p>
<p>Scroll down a little bit until you find <code>Code-runner: Run In Terminal</code>. Make sure that the box is checked (✔).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-184.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Make sure to check the box</strong></em></p>
<p>Now you need to restart your VS Code/VS Code Insiders. Simply close and reopen the program.</p>
<h2 id="heading-how-to-test-your-code">How to Test Your Code</h2>
<p>Simply open VS Code/VS Code Insiders, open any folder, and create any file with the extension <code>.c</code> for the C file and <code>.cpp</code> for the C++ file. </p>
<p>After writing your code, you can run the code directly using the play button you'll find in the upper right corner.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-185.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>This is how you can run any C/C++ program from VS Code/Insiders</strong></em></p>
<p>It will compile and then run the code directly. After running a code, the code runner button would be set default to run directly. So, your computer is 100% ready for compiling and running any C/C++ programming code.  😀</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Thanks for reading the entire article. If it helps you then you can also check out other articles of mine at <a target="_blank" href="https://www.freecodecamp.org/news/author/fahimbinamin/">freeCodeCamp</a>.</p>
<p>If you want to get in touch with me, then you can do so using <a target="_blank" href="https://twitter.com/Fahim_FBA">Twitter</a>, <a target="_blank" href="https://www.linkedin.com/in/fahimfba/">LinkedIn</a>, and <a target="_blank" href="https://github.com/FahimFBA">GitHub</a>. </p>
<p>You can also <a target="_blank" href="https://www.youtube.com/@FahimAmin?sub_confirmation=1">SUBSCRIBE to my YouTube channel</a> (Code With FahimFBA) if you want to learn various kinds of programming languages with a lot of practical examples regularly.</p>
<p>If you want to check out my highlights, then you can do so at my <a target="_blank" href="https://www.polywork.com/fahimbinamin">Polywork timeline</a>.</p>
<p>You can also <a target="_blank" href="https://fahimbinamin.com/">visit my website</a> to learn more about me and what I'm working on.</p>
<p>Thanks a bunch!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Convert an Int to a String in C++ – Integer Cast Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ Type casting or type conversion is the process of converting a variable from one data type to another.  Type casting can be done implicitly or explicitly.  Implicit type casting gets done automatically via the compiler, while explicit type casting is... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-convert-an-int-to-a-string-in-cpp/</link>
                <guid isPermaLink="false">66b0a2cd7e889761ef17c3c1</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Thu, 10 Nov 2022 18:54:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/uday-awal-UjJWhMerJx0-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Type casting or type conversion is the process of converting a variable from one data type to another. </p>
<p>Type casting can be done implicitly or explicitly. </p>
<p>Implicit type casting gets done automatically via the compiler, while explicit type casting is done by the developer.</p>
<p>In this article, you'll learn how to convert an integer to a string in C++ using the <code>stringstream</code> class and the <code>to_string()</code> method.</p>
<h2 id="heading-how-to-convert-an-int-to-a-string-in-c-using-the-stringstream-class">How to Convert an Int to a String in C++ Using the <code>stringstream</code> Class</h2>
<p>Using the <code>stringstream</code> class, we can convert an integer to a string. </p>
<p>Here's an example to help you understand why you'd need to convert an integer to a string:</p>
<pre><code class="lang-c++"><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> age = <span class="hljs-number">20</span>;

    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The user is "</span> + age + <span class="hljs-string">" years old"</span>;
    <span class="hljs-comment">// error: invalid operands of types 'const char*' and 'const char [11]' to binary 'operator+'</span>

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

}
</code></pre>
<p>In the example above, we created an <code>int</code> variable with a value of 20. </p>
<p>When we tried to concatenate that value in a string, we got an error saying "invalid operands of types...". </p>
<p>The error was raised because we tried to perform an operation using two incompatible variable types. The solution would be to convert one variable and make it compatible with the other. </p>
<p>The <code>stringstream</code> class has insertion (<code>&lt;&lt;</code>) and extraction (<code>&gt;&gt;</code>) operators. </p>
<p>The insertion operator is used to pass a variable to the stream. In our case, to pass an integer to the stream. </p>
<p>The extraction operator is used to give out the modified variable. </p>
<p>In other words, a <code>stringstream</code> object would take in a data type, convert it to another data type, and assign the new data type to a variable.</p>
<p>Here's an example: </p>
<pre><code class="lang-c++"><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;sstream&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> age = <span class="hljs-number">20</span>;

    <span class="hljs-comment">// stringstream object</span>
    <span class="hljs-built_in">stringstream</span> stream;

    <span class="hljs-comment">// insertion of integer variable to stream</span>
    stream &lt;&lt; age;

    <span class="hljs-comment">// variable to hold the new variable from the stream</span>
    <span class="hljs-built_in">string</span> age_as_string;

    <span class="hljs-comment">// extraction of string type of the integer variable</span>
    stream &gt;&gt; age_as_string;

    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The user is "</span> + age_as_string + <span class="hljs-string">" years old"</span>;
    <span class="hljs-comment">// The user is 20 years old</span>

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

}
</code></pre>
<p>In the code above, we created a <code>stringstream</code> object called <code>stream</code>. Note that you must include the stringstream class before you can use it: <code>include &lt;sstream&gt;</code>.</p>
<p>We then inserted the integer into the stream: <code>stream &lt;&lt; age;</code>.</p>
<p>After that, we created a new variable called <code>age_as_string</code>. This variable will store the string variable that will be extracted from the stream. </p>
<p>Lastly, we extracted the string type of the integer and stored it in the variable created above: <code>stream &gt;&gt; age_as_string;</code>. </p>
<p>Now we can concatenate the strings and get the desired result: </p>
<pre><code class="lang-c++">    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The user is "</span> + age_as_string + <span class="hljs-string">" years old"</span>;
    <span class="hljs-comment">// The user is 20 years old</span>
</code></pre>
<h2 id="heading-how-to-convert-an-int-to-a-string-in-c-using-the-tostring-method">How to Convert an Int to a String in C++ Using the <code>to_string()</code> Method</h2>
<p>You can use the <a target="_blank" href="https://www.freecodecamp.org/news/int-to-string-in-cpp-how-to-convert-an-integer-with-tostring/">to_string() method</a> to convert int, float, and double data types to strings. </p>
<p>Here's an example: </p>
<pre><code class="lang-c++"><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> age = <span class="hljs-number">20</span>;

    <span class="hljs-built_in">string</span> age_as_string = to_string(age);

    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The user is "</span> + age_as_string + <span class="hljs-string">" years old"</span>;
    <span class="hljs-comment">// The user is 20 years old</span>

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

}
</code></pre>
<p>In the code above, we passed in the <code>age</code> variable to the <code>to_string()</code>: <code>string age_as_string = to_string(age);</code>.</p>
<p>This converted the <code>age</code> variable to a string. Just like the example in the last section, we can now use the variable as a string: </p>
<pre><code class="lang-c++"><span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The user is "</span> + age_as_string + <span class="hljs-string">" years old"</span>;
<span class="hljs-comment">// The user is 20 years old</span>
</code></pre>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about the different ways of converting an integer to a string in C++. </p>
<p>The examples showed how to use the <code>stringstream</code> class and the <code>to_string()</code> method to convert an integer to a string. </p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Quick Sort – Algorithm Time Complexity with C++ and Java Code Example ]]>
                </title>
                <description>
                    <![CDATA[ In this article, you'll learn about one of the most commonly used programming algorithms – the quick sort algorithm.  You'll get to know how the algorithm works with the help of visual guides. You'll also see some code examples that will help you imp... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/quick-sort-algorithm-time-complexity-with-cpp-and-java-code/</link>
                <guid isPermaLink="false">66b0a35c03036c3282dfd7d5</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Thu, 03 Nov 2022 00:43:11 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/kelly-sikkema-377gw1wN0Ic-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, you'll learn about one of the most commonly used programming algorithms – the quick sort algorithm. </p>
<p>You'll get to know how the algorithm works with the help of visual guides. You'll also see some code examples that will help you implement the algorithm in C++ and Java. </p>
<p>Last but not the least, we'll talk about the <a target="_blank" href="https://www.freecodecamp.org/news/big-o-cheat-sheet-time-complexity-chart/">time complexity</a> for the quick sort algorithm in worst, average, and best case complexity scenarios.</p>
<p>Let's get started!</p>
<h2 id="heading-how-does-the-quick-sort-algorithm-work">How Does the Quick Sort Algorithm Work?</h2>
<p>The quick sort algorithm is based on the divide and conquer rule. In a given array of unordered elements (numbers), a pivot is chosen. The pivot is important because other elements will be sorted in respect to its value.</p>
<p>At the end of the sorting operation, all the numbers lower than the pivot will be moved to the left side of the pivot while all numbers higher will be on the right. This is also known as partitioning.</p>
<p>At this stage, the numbers on the right and left of the pivot may/will most likely be unordered.</p>
<p>Next, the unordered numbers before and after the pivot are put into separate arrays – one array for the numbers on the left and another for those on the right.</p>
<p>A pivot will then be chosen in each array and the process from the start is repeated until each number is sorted out separately. Combining all the numbers, you'll have a sorted array in ascending order.</p>
<p>Here's a summary of the above explanations:</p>
<p><strong>Step #1:</strong> An array of unordered numbers is given.</p>
<p><strong>Step #2:</strong> One number is chosen as the pivot. </p>
<p><strong>Step #3:</strong> Numbers lower than the pivot move to the left side of the pivot.</p>
<p><strong>Step #4:</strong> Numbers higher than the pivot move to the right side of the pivot.</p>
<p><strong>Step #5:</strong> The array is broken down into two arrays – the first array will contain elements on the left side of the pivot while the second array will contain elements on the right. </p>
<p><strong>Step #6:</strong> Step #2 to #5 is repeated for each array until every element has been sorted in ascending order.</p>
<p>The steps above may seem confusing. You'll understand it better in the next section with the help of visual guides. </p>
<h2 id="heading-how-does-quick-sort-work">How Does Quick Sort Work?</h2>
<p>In the last section, I gave a brief summary of what happens when you use the quick sort algorithm to sort an array of numbers. But that didn't explain how the sorting operation works under the hood.</p>
<p>In this section, using visual guides, you'll understand how numbers are moved to either the left or right side of the pivot, and how sub arrays are created (also known as partitioning). This will also help you understand the code easily when we get to that part. </p>
<p>Here's the array we'll be working with: <code>9,4,8,3,7,1,6,2,5</code>.</p>
<p>The array above has a set of unordered numbers. So how does quick sort work? </p>
<p>As I explained in the previous section, we have to select one element to act as the pivot. </p>
<p>So let's take 5 as the pivot. We'll also need two variables: <code>X</code> and <code>Y</code>. They will be used to compare and interchange the positions of numbers in respect to the pivot.</p>
<p>Here's what that looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort.png" alt="Image" width="600" height="400" loading="lazy">
<em>quick-sort parameters</em></p>
<p>In the image above, we have three arrows: red, blue, and yellow which denote <code>X</code>, <code>Y</code>, and the pivot, respectively. </p>
<p>The operation is pretty simple: </p>
<ul>
<li>If the value of <code>y</code> is greater than the pivot, increment <code>Y</code>. </li>
<li>If the value of <code>y</code> is less than or equal to the pivot, increment <code>X</code>, and swap the <code>x</code> with <code>y</code>. </li>
</ul>
<p>Let's demonstrate that using the array in the image above: <code>9,4,8,3,7,1,6,2,5</code>. </p>
<h3 id="heading-iteration-1">Iteration #1</h3>
<p>Pivot = 5.<br>Y = 9.</p>
<p>Is Y less than or equal to the pivot? No.</p>
<p>Increment Y.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-iteration-2">Iteration #2</h3>
<p>Pivot = 5.<br>Y = 4.</p>
<p>Is Y less than or equal to the pivot? Yes.</p>
<h5 id="heading-step-1-increment-x">Step #1 - Increment X</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h5 id="heading-step-2-swap-the-value-of-x-and-y">Step #2 - Swap the value of X and Y</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort2i.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h5 id="heading-step-3-increment-y">Step #3 - Increment Y</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort2ii.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Iterations #1 and #2 are basically all that happens during the sorting operation. </p>
<p>In order to help you understand better, I'll go over all the iterations until we have numbers smaller than the pivot on the left and those higher on the right. </p>
<h3 id="heading-iteration-3">Iteration #3</h3>
<p>Pivot = 5.<br>Y = 8.</p>
<p>Is Y less than or equal to the pivot? No.</p>
<p>Increment Y.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-iteration-4">Iteration #4</h3>
<p>Pivot = 5.<br>Y = 3.</p>
<p>Is Y less than or equal to the pivot? Yes.</p>
<h5 id="heading-step-1-increment-x-1">Step #1 - Increment X</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h5 id="heading-step-2-swap-the-value-of-x-and-y-1">Step #2 - Swap the value of X and Y</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort4i.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h5 id="heading-step-3-increment-y-1">Step #3 - Increment Y</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort4ii.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-iteration-5">Iteration #5</h3>
<p>Pivot = 5.<br>Y = 7.</p>
<p>Is Y less than or equal to the pivot? No.</p>
<p>Increment Y. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort5.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-iteration-6">Iteration #6</h3>
<p>Pivot = 5.<br>Y = 1.</p>
<p>Is Y less than or equal to the pivot? Yes.</p>
<h5 id="heading-step-1-increment-x-2">Step #1 - Increment X</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort6.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h5 id="heading-step-2-swap-the-value-of-x-and-y-2">Step #2 - Swap the value of X and Y</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort6i.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h5 id="heading-step-3-increment-y-2">Step #3 - Increment Y</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort6ii.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-iteration-7">Iteration #7</h3>
<p>Pivot = 5.<br>Y = 6.</p>
<p>Is Y less than or equal to the pivot? No.</p>
<p>Increment Y.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-iteration-8">Iteration #8</h3>
<p>Pivot = 5.<br>Y = 6.</p>
<p>Is Y less than or equal to the pivot? Yes.</p>
<h5 id="heading-step-1-increment-x-3">Step #1 - Increment X</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort8.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h5 id="heading-step-2-swap-the-value-of-x-and-y-3">Step #2 - Swap the value of X and Y</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort8i.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h5 id="heading-step-3-increment-y-3">Step #3 - Increment Y</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort8ii.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-iteration-9">Iteration #9</h3>
<p>At this point, <code>Y</code> is now pointing to the pivot. You can either increment <code>X</code> and swap if with <code>Y</code>, or you can use the format in the previous iterations. I'll go with the latter. </p>
<p>Pivot = 5.<br>Y = 5.</p>
<p>Is Y less than or equal to the pivot? Yes.</p>
<h5 id="heading-step-1-swap-the-value-of-x-and-y">Step #1 - Swap the value of X and Y</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/quick-sort9i.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Our array now looks like this: <code>4,3,1,2,5,8,6,9,7</code></p>
<p>If you look at the current state of the array, you'd realize that:</p>
<ul>
<li>The pivot is now at the center. </li>
<li>All the numbers on the left side of the pivot are lower than the pivot. </li>
<li>All the numbers on the right side of the pivot are higher than the pivot.</li>
</ul>
<p>But we're not yet done. The numbers are still unordered. To sort them, we'll break the array down into two sub arrays (excluding the pivot element).</p>
<p>The first array will have all the numbers on the left side of the pivot: <code>4,3,1,2</code>.</p>
<p>The second array will have all the numbers on the right side of the pivot: <code>8,6,9,7</code>.</p>
<p>Let's sort the first array. As usual, you need a pivot.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/sub-array-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-iteration-1-1">Iteration #1</h3>
<p>Pivot = 2.<br>Y = 4.</p>
<p>Is Y less than or equal to the pivot? No.</p>
<p>Increment Y. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/sub-array.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-iteration-2-1">Iteration #2</h3>
<p>Pivot = 2.<br>Y = 3.</p>
<p>Is Y less than or equal to the pivot? No.</p>
<p>Increment Y. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/sub-array2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-iteration-3-1">Iteration #3</h3>
<p>Pivot = 2.<br>Y = 1.</p>
<p>Is Y less than or equal to the pivot? Yes.</p>
<h5 id="heading-step-1-increment-x-4">Step #1 - Increment X</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/sub-array3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h5 id="heading-step-2-swap-the-value-of-x-and-y-4">Step #2 - Swap the value of X and Y</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/sub-array3i.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h5 id="heading-step-3-increment-y-4">Step #3 - Increment Y</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/sub-array4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-iteration-3-2">Iteration #3</h3>
<p>Pivot = 2.<br>Y = 2.</p>
<p>Is Y less than or equal to the pivot? Yes.</p>
<h5 id="heading-step-1-swap-the-value-of-x-and-y-1">Step #1 - Swap the value of X and Y</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/sub-array6.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Again, we break down the array into sub arrays excluding the pivot (2). Note that we're still dealing with the numbers on the left side of the initial array.</p>
<p>The first array will have this: <code>1</code>.</p>
<p>The second array will have these: <code>4,3</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/partition.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The first array has only one element so it is already sorted. Let's sort the second array:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/array.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-iteration-1-2">Iteration #1</h3>
<p>Pivot = 3.<br>Y = 4.</p>
<p>Is Y less than or equal to the pivot? No.</p>
<p>Increment Y.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/array2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-iteration-2-2">Iteration #2</h3>
<p>Pivot = 3.<br>Y = 3.</p>
<p>Is Y less than or equal to the pivot? Yes.</p>
<h5 id="heading-step-1-swap-the-value-of-x-and-y-2">Step #1 - Swap the value of X and Y</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/array3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We'll now have the numbers in this order:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/sorted.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>All the numbers on the left side of the first pivot have been sorted in ascending order: <code>1,2,3,4,5,8,6,9,7</code>.</p>
<p>The process is the same for sorting the numbers on the right side. It's time to attempt doing it yourself! Just follow the steps in previous examples. </p>
<h2 id="heading-quick-sort-algorithm-java-code-example">Quick Sort Algorithm Java Code Example</h2>
<p>Here is a code example in Java for the quick sort algorithm. I've included comments to make the code easier to understand.</p>
<p>If you have followed along in the previous sections then this should be self-explanatory.</p>
<pre><code class="lang-java"><span class="hljs-comment">// Quick sort in Java</span>

<span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Quicksort</span> </span>{

    <span class="hljs-comment">// method for swapping elements x and y</span>
    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">swap</span><span class="hljs-params">(<span class="hljs-keyword">int</span>[] arr, <span class="hljs-keyword">int</span> x, <span class="hljs-keyword">int</span> y)</span> </span>{
        <span class="hljs-keyword">int</span> temp = arr[x];
        arr[x] = arr[y];
        arr[y] = temp;
    }

  <span class="hljs-comment">// partition method</span>
  <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">partition</span><span class="hljs-params">(<span class="hljs-keyword">int</span> array[], <span class="hljs-keyword">int</span> low, <span class="hljs-keyword">int</span> high)</span> </span>{

    <span class="hljs-comment">//pivot</span>
    <span class="hljs-keyword">int</span> pivot = array[high];

    <span class="hljs-keyword">int</span> x = (low - <span class="hljs-number">1</span>);



    <span class="hljs-comment">// loop for comparing all elements with pivot element</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> y = low; y &lt; high; y++) {
      <span class="hljs-keyword">if</span> (array[y] &lt;= pivot) {
        x++;

        swap(array, x, y);
      }

    }

    <span class="hljs-keyword">int</span> temp = array[x + <span class="hljs-number">1</span>];
    array[x + <span class="hljs-number">1</span>] = array[high];
    array[high] = temp;

    <span class="hljs-keyword">return</span> (x + <span class="hljs-number">1</span>);
  }

  <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">quickSort</span><span class="hljs-params">(<span class="hljs-keyword">int</span> array[], <span class="hljs-keyword">int</span> low, <span class="hljs-keyword">int</span> high)</span> </span>{
    <span class="hljs-keyword">if</span> (low &lt; high) {

      <span class="hljs-keyword">int</span> array_partition = partition(array, low, high);

      <span class="hljs-comment">// quick sort elements on the left recursively</span>
      quickSort(array, low, array_partition - <span class="hljs-number">1</span>);

      <span class="hljs-comment">// quick sort elements on the right recursively</span>
      quickSort(array, array_partition + <span class="hljs-number">1</span>, high);
    }
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String args[])</span> </span>{

    <span class="hljs-keyword">int</span>[] my_array = { <span class="hljs-number">9</span>,<span class="hljs-number">4</span>,<span class="hljs-number">8</span>,<span class="hljs-number">3</span>,<span class="hljs-number">7</span>,<span class="hljs-number">1</span>,<span class="hljs-number">6</span>,<span class="hljs-number">2</span>,<span class="hljs-number">5</span> };

    <span class="hljs-keyword">int</span> size = my_array.length;

    Quicksort.quickSort(my_array, <span class="hljs-number">0</span>, size - <span class="hljs-number">1</span>);

    System.out.println(<span class="hljs-string">"Sorted Array: "</span>);
    System.out.println(Arrays.toString(my_array));
    <span class="hljs-comment">// Sorted Array: [1, 2, 3, 4, 5, 6, 7, 8, 9]</span>
  }
}
</code></pre>
<h2 id="heading-quick-sort-algorithm-c-code-example">Quick Sort Algorithm C++ Code Example</h2>
<p>Here's an example of the quick sort algorithm in C++:</p>
<pre><code class="lang-c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;bits/stdc++.h&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-comment">// function for swapping elements x and y</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">swap</span><span class="hljs-params">(<span class="hljs-keyword">int</span>* x, <span class="hljs-keyword">int</span>* y)</span>
</span>{
    <span class="hljs-keyword">int</span> temp = *x;
    *x = *y;
    *y = temp;
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">partition</span><span class="hljs-params">(<span class="hljs-keyword">int</span> arr[], <span class="hljs-keyword">int</span> low, <span class="hljs-keyword">int</span> high)</span>
</span>{
    <span class="hljs-comment">// pivot</span>
    <span class="hljs-keyword">int</span> pivot = arr[high]; 
    <span class="hljs-keyword">int</span> x = (low- <span class="hljs-number">1</span>); 

    <span class="hljs-comment">// loop for comparing all elements with pivot element</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> y = low; y &lt;= high - <span class="hljs-number">1</span>; y++) {

        <span class="hljs-keyword">if</span> (arr[y] &lt; pivot) {
            x++; 
            swap(&amp;arr[x], &amp;arr[y]);
        }
    }
    swap(&amp;arr[x + <span class="hljs-number">1</span>], &amp;arr[high]);
    <span class="hljs-keyword">return</span> (x + <span class="hljs-number">1</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">quickSort</span><span class="hljs-params">(<span class="hljs-keyword">int</span> arr[], <span class="hljs-keyword">int</span> low, <span class="hljs-keyword">int</span> high)</span>
</span>{
    <span class="hljs-keyword">if</span> (low &lt; high) {

        <span class="hljs-keyword">int</span> array_partition = partition(arr, low, high);

        <span class="hljs-comment">// quick sort elements on the left recursively</span>
        quickSort(arr, low, array_partition - <span class="hljs-number">1</span>);

        <span class="hljs-comment">// quick sort elements on the right recursively</span>
        quickSort(arr, array_partition + <span class="hljs-number">1</span>, high);
    }
}

<span class="hljs-comment">// print array function </span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">printArray</span><span class="hljs-params">(<span class="hljs-keyword">int</span> arr[], <span class="hljs-keyword">int</span> size)</span>
</span>{
    <span class="hljs-keyword">int</span> i;
    <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; size; i++)
        <span class="hljs-built_in">cout</span> &lt;&lt; arr[i] &lt;&lt; <span class="hljs-string">" "</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-built_in">endl</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> arr[] = { <span class="hljs-number">9</span>,<span class="hljs-number">4</span>,<span class="hljs-number">8</span>,<span class="hljs-number">3</span>,<span class="hljs-number">7</span>,<span class="hljs-number">1</span>,<span class="hljs-number">6</span>,<span class="hljs-number">2</span>,<span class="hljs-number">5</span> };

    <span class="hljs-keyword">int</span> size = <span class="hljs-keyword">sizeof</span>(arr) / <span class="hljs-keyword">sizeof</span>(arr[<span class="hljs-number">0</span>]);

    quickSort(arr, <span class="hljs-number">0</span>, size - <span class="hljs-number">1</span>);
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Sorted array: "</span>;
    printArray(arr, size);
    <span class="hljs-comment">// Sorted array: 1 2 3 4 5 6 7 8 9 </span>

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<h2 id="heading-time-complexity-for-quick-sort-algorithm">Time Complexity for Quick Sort Algorithm</h2>
<p>Worst case =&gt; O(n<sup>2</sup>)</p>
<p>Average case =&gt; O(n*log(n))</p>
<p>Best case =&gt; O(n*log(n))</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about the quick sort algorithm. </p>
<p>We gave a brief explanation of how the algorithm works. After that, we saw an example that explained how it works under the hood using visual guides to sort an unordered array.</p>
<p>We also saw how to implement the quick sort algorithm in Java and C++.</p>
<p>Lastly, we listed the quick sort time complexity for worst, average, and best case.</p>
<p>Happy coding! </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Bubble Sort – Algorithm in Java, C++, Python with Example Code ]]>
                </title>
                <description>
                    <![CDATA[ Bubble sort is a type of sorting algorithm you can use to arrange a set of values in ascending order. If you want, you can also implement bubble sort to sort the values in descending order. A real-world example of a bubble sort algorithm is how the c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/bubble-sort-algorithm-in-java-cpp-python-with-example-code/</link>
                <guid isPermaLink="false">66adf079febac312b7307599</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Thu, 29 Sep 2022 17:34:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/bubbleSortCover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Bubble sort is a type of sorting algorithm you can use to arrange a set of values in ascending order. If you want, you can also implement bubble sort to sort the values in descending order.</p>
<p>A real-world example of a bubble sort algorithm is how the contact list on your phone is sorted in alphabetical order. Or the sorting of files on your phone according to the time they were added.</p>
<p>In this article, I will explain all you need to know about the bubble sort algorithm with some infographics I’ve prepared. I will then show you example code of the bubble sort algorithm in Python, Java, and C++.</p>
<h2 id="heading-table-of-contents">Table Of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-how-the-bubble-sort-algorithm-works">How the Bubble Sort Algorithm Works</a><ul>
<li><a class="post-section-overview" href="#heading-first-iteration-of-the-sorting">First Iteration of the Sorting</a></li>
<li><a class="post-section-overview" href="#heading-second-iteration-of-the-sorting-and-the-rest">Second Iteration of the Sorting and the Rest</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-python-code-example-of-bubble-sort-algorithm">Python Code Example of Bubble Sort Algorithm</a></li>
<li><a class="post-section-overview" href="#heading-java-code-example-of-bubble-sort-algorithm">Java Code Example of Bubble Sort Algorithm</a></li>
<li><a class="post-section-overview" href="#heading-c-code-example-of-bubble-sort-algorithm">C++ Code Example of Bubble Sort Algorithm</a></li>
<li><a class="post-section-overview" href="#heading-final-thoughts">Final Thoughts</a></li>
</ul>
<h2 id="heading-how-the-bubble-sort-algorithm-works">How the Bubble Sort Algorithm Works</h2>
<p>To implement a bubble sort algorithm, developers often write a function, and then a loop within a loop – inner loop and outer loop. You will see it in action when I show you the code in Python, C++, and Java.</p>
<p>Let's say we want to sort a series of numbers 5, 3, 4, 1, and 2 so that they are arranged in ascending order…</p>
<p>The sorting begins the first iteration by comparing the first two values. If the first value is greater than the second, the algorithm pushes the first value to the index of the second value.</p>
<h3 id="heading-first-iteration-of-the-sorting">First Iteration of the Sorting</h3>
<p><strong>Step 1</strong>:  In the case of 5, 3, 4, 1, and 2, 5 is greater than 3. So 5 takes the position of 3 and the numbers become 3, 5, 4, 1, and 2.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/bubble1.png" alt="bubble1" width="600" height="400" loading="lazy"> </p>
<p><strong>Step 2</strong>: The algorithm now has 3, 5, 4, 1, and 2 to compare, this time around, it compares the next two values, which are 5 and 4. 5 is greater than 4, so 5 takes the index of 4 and the values now become 3, 4, 5, 1, and 2.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/bubble2.png" alt="bubble2" width="600" height="400" loading="lazy"> </p>
<p><strong>Step 3</strong>: The algorithm now has 3, 4, 5, 1, and 2 to compare. It compares the next two values, which are 5 and 1. 5 is greater than 1, so 5 takes the index of 1 and the numbers become 3, 4, 1, 5, and 2.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/bubble3.png" alt="bubble3" width="600" height="400" loading="lazy"> </p>
<p><strong>Step 4</strong>: The algorithm now has 3, 4, 1, 5, and 2 to compare. It compares the next two values, which are 5 and 2. 5 is greater than 2, so 5 takes the index of 2 and the numbers become 3, 4, 1, 2, and 5.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/bubble4.png" alt="bubble4" width="600" height="400" loading="lazy"> </p>
<p>That’s the first iteration. And the numbers are now arranged as 3, 4, 1, 2, and 5 – from the initial 5, 3, 4, 1, and 2. As you might realize, 5 should be the last number if the numbers are sorted in ascending order. This means the first iteration is really completed.    </p>
<h3 id="heading-second-iteration-of-the-sorting-and-the-rest">Second Iteration of the Sorting and the Rest</h3>
<p>The algorithm starts the second iteration with the last result of 3, 4, 1, 2, and 5. This time around, 3 is smaller than 4, so no swapping happens. This means the numbers will remain the same.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/bubbleb1.png" alt="bubbleb1" width="600" height="400" loading="lazy"> </p>
<p>The algorithm proceeds to compare 4 and 1. 4 is greater than 1, so 4 is swapped for 1 and the numbers become 3, 1, 4, 2, and 5.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/bubbleb2.png" alt="bubbleb2" width="600" height="400" loading="lazy"> </p>
<p>The algorithm now proceeds to compare 4 and 2. 4 is greater than 2, so 4 is swapped for 2 and the numbers become 3, 1, 2, 4, and 5. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/bubbleb4.png" alt="bubbleb4" width="600" height="400" loading="lazy"> </p>
<p>4 is now in the right place, so no swapping occurs between 4 and 5 because 4 is smaller than 5. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/bubbleb5.png" alt="bubbleb5" width="600" height="400" loading="lazy"> </p>
<p>That’s how the algorithm continues to compare the numbers until they are arranged in ascending order of 1, 2, 3, 4, and 5.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/bubblebFinal.png" alt="bubblebFinal" width="600" height="400" loading="lazy"> </p>
<h2 id="heading-python-code-example-of-bubble-sort-algorithm">Python Code Example of Bubble Sort Algorithm</h2>
<p>Here’s a code example showing the implementation of the bubble sort algorithm in Python:</p>
<pre><code class="lang-py"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bubble_sort</span>(<span class="hljs-params">arr</span>):</span>
    arr_len = len(arr)
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(arr_len<span class="hljs-number">-1</span>):
        flag = <span class="hljs-number">0</span>
        <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">0</span>, arr_len-i<span class="hljs-number">-1</span>):
            <span class="hljs-keyword">if</span> arr[j] &gt; arr[j+<span class="hljs-number">1</span>]:
                arr[j+<span class="hljs-number">1</span>], arr[j] = arr[j], arr[j+<span class="hljs-number">1</span>]
                flag = <span class="hljs-number">1</span>
                <span class="hljs-keyword">if</span> flag == <span class="hljs-number">0</span>:
                    <span class="hljs-keyword">break</span>
    <span class="hljs-keyword">return</span> arr

arr = [<span class="hljs-number">5</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
print(<span class="hljs-string">"List sorted with bubble sort in ascending order: "</span>, bubble_sort(arr))

<span class="hljs-comment"># Output: List sorted with bubble sort in ascending order:  [1, 2, 3, 4, 5]</span>
</code></pre>
<p>To make the sorting appear in descending order, just replace the greater than symbol (&gt;) with lesser than (&lt;):</p>
<pre><code class="lang-py"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bubble_sort</span>(<span class="hljs-params">arr</span>):</span>
    arr_len = len(arr)
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(arr_len<span class="hljs-number">-1</span>):
        flag = <span class="hljs-number">0</span>
        <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">0</span>, arr_len-i<span class="hljs-number">-1</span>):
            <span class="hljs-keyword">if</span> arr[j] &lt; arr[j+<span class="hljs-number">1</span>]:
                arr[j+<span class="hljs-number">1</span>], arr[j] = arr[j], arr[j+<span class="hljs-number">1</span>]
                flag = <span class="hljs-number">1</span>
                <span class="hljs-keyword">if</span> flag == <span class="hljs-number">0</span>:
                    <span class="hljs-keyword">break</span>
    <span class="hljs-keyword">return</span> arr

arr = [<span class="hljs-number">5</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
print(<span class="hljs-string">"List sorted with bubble sort in descending order: "</span>, bubble_sort(arr))

<span class="hljs-comment"># Output: List sorted with bubble sort in descending order:  [5, 4, 3, 2, 1]</span>
</code></pre>
<p>Here’s a version of the code where I added comments to so you can know what’s going on: </p>
<pre><code class="lang-py"><span class="hljs-comment"># Define a function to create the sorting and pass in an array as the parameter</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bubble_sort</span>(<span class="hljs-params">arr</span>):</span>
    <span class="hljs-comment"># Get the length of the array</span>
    arr_len = len(arr)
    <span class="hljs-comment"># Loop through the array to access the elements in it, including the last one - outer loop</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(arr_len<span class="hljs-number">-1</span>):
        <span class="hljs-comment"># declare a flag variable to check if a swap has occured - for optimization</span>
        flag = <span class="hljs-number">0</span>
        <span class="hljs-comment"># create a loop to compare each element of the array till the last one</span>
        <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">0</span>, arr_len-i<span class="hljs-number">-1</span>):
            <span class="hljs-comment"># compare 2 adjacent elements and sort them in ascending order</span>
            <span class="hljs-keyword">if</span> arr[j] &gt; arr[j+<span class="hljs-number">1</span>]:
                <span class="hljs-comment"># Swap the elements if they are not in the right order</span>
                arr[j+<span class="hljs-number">1</span>], arr[j] = arr[j], arr[j+<span class="hljs-number">1</span>]
                flag = <span class="hljs-number">1</span>
                <span class="hljs-comment"># break out of the loop at 0</span>
                <span class="hljs-keyword">if</span> flag == <span class="hljs-number">0</span>:
                    <span class="hljs-keyword">break</span>
    <span class="hljs-comment"># return value must be in the outer loop block</span>
    <span class="hljs-keyword">return</span> arr

arr = [<span class="hljs-number">5</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
print(<span class="hljs-string">"List sorted with bubble sort in ascending order: "</span>, bubble_sort(arr))

<span class="hljs-comment"># Output: List sorted with bubble sort in ascending order:  [1, 2, 3, 4, 5]</span>
</code></pre>
<h2 id="heading-java-code-example-of-bubble-sort-algorithm">Java Code Example of Bubble Sort Algorithm</h2>
<p>To implement the bubble sort algorithm in Java, you have to write more code than you did with Python.</p>
<p>That’s why I added comments to let you know about the steps as they are executed:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
  <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> bubbleSort(int array[]) {
    int size = array.length;
    <span class="hljs-comment">// loop over each element of the array to access them</span>
    <span class="hljs-keyword">for</span> (int i = <span class="hljs-number">0</span>; i &lt; size - <span class="hljs-number">1</span>; i++)
      <span class="hljs-comment">// compare the elements of the array with a loop</span>
      <span class="hljs-keyword">for</span> (int j = <span class="hljs-number">0</span>; j &lt; size - i - <span class="hljs-number">1</span>; j++)
        <span class="hljs-comment">// compare two adjacent elements in the array</span>
        <span class="hljs-keyword">if</span> (array[j] &gt; array[j + <span class="hljs-number">1</span>]) {
          <span class="hljs-comment">// Swap if the elements aren't in the right order</span>
          int temp = array[j];
          array[j] = array[j + <span class="hljs-number">1</span>];
          array[j + <span class="hljs-number">1</span>] = temp;
        }
  }

  public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span> args[]) {
    int[] data = { <span class="hljs-number">5</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span> };
    <span class="hljs-comment">// call the method using class name</span>
    Main.bubbleSort(data);

    System.out.println(<span class="hljs-string">"Array sorted with bubble sort: "</span>);
    System.out.println(Arrays.toString(data));
  }
}

<span class="hljs-comment">// Output: Array sorted with bubble sort: [1, 2, 3, 4, 5]</span>
</code></pre>
<h2 id="heading-c-code-example-of-bubble-sort-algorithm">C++ Code Example of Bubble Sort Algorithm</h2>
<p>Like I did for Java, I also added comments to the implementation of the bubble sort algorithm in C++ because it’s more verbose than that of Python and Java:</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-comment">// create a function to execute bubble sort</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">bubble_sort</span><span class="hljs-params">(<span class="hljs-keyword">int</span> <span class="hljs-built_in">array</span>[], <span class="hljs-keyword">int</span> size)</span> </span>{
  <span class="hljs-comment">// loop over each element of the array to access them - outer loop</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> step = <span class="hljs-number">0</span>; step &lt; (size<span class="hljs-number">-1</span>); ++step) {
    <span class="hljs-comment">// check if swapping occurs</span>
    <span class="hljs-keyword">int</span> swapped = <span class="hljs-number">0</span>;
    <span class="hljs-comment">// loop over each element of the array to compare them - inner loop</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; (size-step<span class="hljs-number">-1</span>); ++i) {
     <span class="hljs-comment">// compare 2 adjacent elements and sort them in ascending order</span>
      <span class="hljs-keyword">if</span> (<span class="hljs-built_in">array</span>[i] &gt; <span class="hljs-built_in">array</span>[i + <span class="hljs-number">1</span>]) {

        <span class="hljs-comment">//Swap the elements if they are not in the right order</span>
        <span class="hljs-keyword">int</span> temp = <span class="hljs-built_in">array</span>[i];
        <span class="hljs-built_in">array</span>[i] = <span class="hljs-built_in">array</span>[i + <span class="hljs-number">1</span>];
        <span class="hljs-built_in">array</span>[i + <span class="hljs-number">1</span>] = temp;

        swapped = <span class="hljs-number">1</span>;
      }
    }

    <span class="hljs-comment">// break out of the loop if no swapping occurs anymore</span>
    <span class="hljs-keyword">if</span> (swapped == <span class="hljs-number">0</span>)
      <span class="hljs-keyword">break</span>;
  }
}

<span class="hljs-comment">// print an array</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">printArray</span><span class="hljs-params">(<span class="hljs-keyword">int</span> <span class="hljs-built_in">array</span>[], <span class="hljs-keyword">int</span> size)</span> </span>{
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; size; ++i) {
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"  "</span> &lt;&lt; <span class="hljs-built_in">array</span>[i];
  }
  <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"\n"</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> data[] = {<span class="hljs-number">5</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>};
  <span class="hljs-comment">// find the length of the array</span>
  <span class="hljs-keyword">int</span> size = <span class="hljs-keyword">sizeof</span>(data) / <span class="hljs-keyword">sizeof</span>(data[<span class="hljs-number">0</span>]);

  <span class="hljs-comment">// call the function   </span>
  bubble_sort(data, size);

  <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Array sorted with bubble sort: \n"</span>;
  printArray(data, size);
}

<span class="hljs-comment">// Output: Array sorted with bubble sort: 1  2  3  4  5</span>
</code></pre>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>I won’t say the implementation of the bubble sort algorithm is either simple or hard. For an experienced programmer, it’s not hard, but for a beginner, it could be intimidating at first.</p>
<p>However, to really understand how the algorithm works, you need to know that:</p>
<ul>
<li>you need to write a function to pass the data [or array] into</li>
<li>you need to write an outer loop to access the elements</li>
<li>you need to write an inner loop to compare the elements  </li>
<li>you need to call the function and pass in the data (array)</li>
</ul>
<p>I hope this article helps you understand the bubble sort algorithm and how to implement it.</p>
<p>Thank you for reading.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ C++ Vector – How to Initialize a Vector in a Constructor in C++ ]]>
                </title>
                <description>
                    <![CDATA[ When you're working with a collection of variables or data in programming, you usually store them in specific data types.  In C++, you can store them in arrays, structures, vectors, strings and so on. While these data structures have their distinctiv... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/cpp-vector-how-to-initialize-a-vector-in-a-constructor/</link>
                <guid isPermaLink="false">66b0a28ad7edba94d20b3baa</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Fri, 27 May 2022 20:08:33 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/05/uday-awal-UjJWhMerJx0-unsplash--2-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When you're working with a collection of variables or data in programming, you usually store them in specific data types. </p>
<p>In C++, you can store them in arrays, structures, vectors, strings and so on. While these data structures have their distinctive features, we'll focus mainly on the various methods of initializing vectors.</p>
<p>Before that, let's talk briefly about vectors and what makes them stand out when dealing with data collections in C++.</p>
<h2 id="heading-what-are-vectors-in-c">What are Vectors in C++?</h2>
<p>Unlike arrays in C++ where the memory allocated to the collection is static, vectors let us create more dynamic data structures. </p>
<p>Here's an array in C++:</p>
<pre><code class="lang-c++"><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-built_in">string</span> names[<span class="hljs-number">2</span>] = {<span class="hljs-string">"Jane"</span>, <span class="hljs-string">"John"</span>};
    <span class="hljs-built_in">cout</span> &lt;&lt; names[<span class="hljs-number">1</span>];
    <span class="hljs-comment">// John</span>
}
</code></pre>
<p>The array in the code above was created and allocated space enough to contain only two items. Attempting to assign new values through a new index would throw an error our way.</p>
<p>With vectors, things are a bit different. We don't have to specify the vector's capacity when it's defined. Under the hood, the vector's allocated memory changes as the size of the vector changes.</p>
<h2 id="heading-syntax-for-vectors-in-c">Syntax for Vectors in C++</h2>
<p>Declaring a <code>vector</code> is different from initializing it. Declaring a <code>vector</code> means creating a new <code>vector</code> while initializations involves passing items into the <code>vector</code>. </p>
<p>Here's what the syntax looks like:</p>
<pre><code class="lang-txt">vector &lt;data_type&gt; vector_name
</code></pre>
<p>Every new <code>vector</code> must be declared starting with the <strong>vector</strong> keyword. This is followed by angle brackets which contain the the type of data the vector can accept like strings, integers, and so on. Lastly, the vector name - we can call this whatever we want. </p>
<p>Note that you must put <code>include &lt;vector&gt;</code> at the top of your file to be able to use vectors.</p>
<h2 id="heading-how-to-initialize-a-vector-in-c">How to Initialize a Vector in C++</h2>
<p>In this section, we'll go over the different ways of initializing a <code>vector</code> in C++. We'll divide them into sub-sections with some examples for each sub-section.</p>
<p>Let's start with the most basic. </p>
<h3 id="heading-how-to-initialize-a-vector-in-c-using-the-pushback-method">How to Initialize a Vector in C++ Using the <code>push_back()</code> Method</h3>
<p><code>push_back()</code> is one out of the many methods you can use to interact with vectors in C++. It takes in the new item to be passed in as a parameter. This allows us to push new items to the last index of a <code>vector</code>. </p>
<p>Here's an example:</p>
<pre><code class="lang-c++"><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-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; myVector;

    myVector.push_back(<span class="hljs-number">5</span>);
    myVector.push_back(<span class="hljs-number">10</span>);
    myVector.push_back(<span class="hljs-number">15</span>);

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> x : myVector)
        <span class="hljs-built_in">cout</span> &lt;&lt; x &lt;&lt; <span class="hljs-string">" "</span>;
        <span class="hljs-comment">// 5 10 15 </span>
}
</code></pre>
<p>In the code above, we created an empty <code>vector</code>: <code>vector&lt;int&gt; myVector;</code>. </p>
<p>Using the <code>push_back()</code>, we passed in three new numbers to the <code>vector</code>. </p>
<p>We the looped through these new numbers and logged them out to the console. </p>
<h3 id="heading-how-to-initialize-a-vector-when-declaring-the-vector-in-c">How to Initialize a Vector When Declaring the Vector in C++</h3>
<p>Just like arrays, we can assign values to a vector when it is being declared. </p>
<p>Here's an example:</p>
<pre><code class="lang-c++"><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-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; myVector{ <span class="hljs-number">5</span>, <span class="hljs-number">10</span>, <span class="hljs-number">15</span> };

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> x : myVector)
        <span class="hljs-built_in">cout</span> &lt;&lt; x &lt;&lt; <span class="hljs-string">" "</span>;
        <span class="hljs-comment">// 5 10 15 </span>
}
</code></pre>
<p>In this example, both declaration and initialization were done at the same time. </p>
<p>At the point of declaring the <code>vector</code>, we passed in three numbers and then looped through and printed them out. </p>
<p>You'll notice that I put <code>int</code> between the angle brackets. This is to show that the data the <code>vector</code> will hold is specifically integers. </p>
<h3 id="heading-how-to-initialize-a-vector-from-an-array-in-c">How to Initialize a Vector From an Array in C++</h3>
<p>In this section, we'll first create and initialize an array. Then we'll copy all the items in the array into our vector using two vector methods – <code>begin()</code> and <code>end()</code>.</p>
<p>Let's see how that works. </p>
<pre><code class="lang-c++"><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-keyword">int</span> myArray[] = { <span class="hljs-number">5</span>, <span class="hljs-number">10</span>, <span class="hljs-number">15</span> };

    <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">myVector</span><span class="hljs-params">(begin(myArray), end(myArray))</span></span>;


    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> x : myVector)
        <span class="hljs-built_in">cout</span> &lt;&lt; x &lt;&lt; <span class="hljs-string">" "</span>;
        <span class="hljs-comment">// 5 10 15 </span>
}
</code></pre>
<p>We can also initialize a <code>vector</code> from another vector using the same methods above. You'll have to define the first <code>vector</code> then use the <code>begin()</code> and <code>end()</code> methods to copy its values into the second <code>vector</code>.</p>
<h3 id="heading-how-to-initialize-a-vector-by-specifying-the-size-and-value-in-c">How to Initialize a Vector by Specifying the Size and Value in C++</h3>
<p>We can specify the size and items of a <code>vector</code> during its declaration. This is mainly in situations where the <code>vector</code> is required to have a specific value all through. </p>
<p>Here's an example:</p>
<pre><code class="lang-c++"><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-keyword">int</span> num_of_items = <span class="hljs-number">5</span>; 

  <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">myVector</span><span class="hljs-params">(num_of_items, <span class="hljs-number">2</span>)</span></span>; 

      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> x : myVector)
        <span class="hljs-built_in">cout</span> &lt;&lt; x &lt;&lt; <span class="hljs-string">" "</span>;
<span class="hljs-comment">//         2 2 2 2 2 </span>
}
</code></pre>
<p>In the code above, we first defined a variable and passed a value of 5 to it. This acts as the maximum number of values the <code>vector</code> will have. </p>
<p>We then declared our <code>vector</code>: <code>vector myVector(num_of_items, 2);</code>. The first parameter is the maximum number of items variable while the second parameter is the actual item to be stored in the <code>vector</code>.</p>
<p>We looped through and logged out the items in the <code>vector</code>. We got 2 printed five times. </p>
<h3 id="heading-how-to-initialize-a-vector-using-a-constructor-in-c">How to Initialize a Vector Using a Constructor in C++</h3>
<p>We can also initialize vectors in constructors. We can make the values to be a bit dynamic. This way, we don't have to hardcode the vector's items. </p>
<p>Here's an example:</p>
<pre><code class="lang-c++"><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-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vector</span> {</span>
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; myVec;

<span class="hljs-keyword">public</span>:
    Vector(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; newVector) {
        myVec = newVector;
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; myVec.size(); i++)
            <span class="hljs-built_in">cout</span> &lt;&lt; myVec[i] &lt;&lt; <span class="hljs-string">" "</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">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; vec;

    vec.push_back(<span class="hljs-number">5</span>);
    vec.push_back(<span class="hljs-number">10</span>);
    vec.push_back(<span class="hljs-number">15</span>);

    <span class="hljs-function">Vector <span class="hljs-title">vect</span><span class="hljs-params">(vec)</span></span>;
    vect.print();
    <span class="hljs-comment">// 5 10 15 </span>
}
</code></pre>
<p>Let's break the code down. </p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vector</span> {</span>
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; myVec;

<span class="hljs-keyword">public</span>:
    Vector(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; newVector) {
        myVec = newVector;
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; myVec.size(); i++)
            <span class="hljs-built_in">cout</span> &lt;&lt; myVec[i] &lt;&lt; <span class="hljs-string">" "</span>;
    }

};
</code></pre>
<p>We created a class called <strong>Vector</strong>. Then we created a vector variable called <code>myVec</code>. </p>
<p>After that, we defined our constructor. The constructor has two methods – one that takes in an initialized <code>vector</code> and another that prints out the items in the <code>vector</code>. </p>
<pre><code class="lang-c++"><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">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; vec;

    vec.push_back(<span class="hljs-number">5</span>);
    vec.push_back(<span class="hljs-number">10</span>);
    vec.push_back(<span class="hljs-number">15</span>);

    <span class="hljs-function">Vector <span class="hljs-title">vect</span><span class="hljs-params">(vec)</span></span>;
    vect.print();
    <span class="hljs-comment">// 5 10 15 </span>
}
</code></pre>
<p>Lastly, as you can see in the code above, we created a new <code>vector</code> and pushed in new items to it. We then went on to log these items to the console.</p>
<p>The logic in <code>main</code> was created in the <strong>Vector</strong> class which also has a constructor. </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we talked about vectors in C++. </p>
<p>We started by differentiating arrays and vectors. Arrays have a static size while vectors are more dynamic and can expand as items are added. </p>
<p>We then went over a few methods which we can use to initialize a <code>vector</code> in C++ with examples for each section. </p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
