Jekyll2022-11-17T11:28:35-06:00https://stevenbitner.github.io/feed.xmlSteve Bitner / GitHubSteve BitnerGit Primer2022-10-12T00:00:00-05:002022-10-12T00:00:00-05:00https://stevenbitner.github.io/posts/git-primer<p>This primer introduces the basic commands and workflows in the Git™ Version Control System (VCS).
For a more detailed look at the workings of Git, refer to the free resource hosted as part of the Git open-source project - <a href="https://git-scm.com/book">git scm book</a>.</p>
<h1 id="git---quick-primer">Git™ - Quick Primer</h1>
<p>A fast-paced introduction to version control and git.
If you want the full blown experience, see the <a href="https://git-scm.com/book">git scm book</a>.</p>
<h2 id="what-is-version-control">What is version control</h2>
<p>Version control is maintaining a detailed report of changes that happen to your codebase.
Good version control practice allows you to roll back mistakes, work on features in parallel, and combine them into a final product.</p>
<h2 id="how-does-git-record-history">How does Git record history?</h2>
<ul>
<li>A git <strong>repository</strong> consists of a collection of <strong>branches</strong>.</li>
<li>Each <strong>branch</strong> is a sequential series of <strong>commits</strong>.</li>
<li>An individual <strong>commit</strong> describes <em>what changed</em> since the last commit.</li>
<li>Each <strong>commit</strong> has a unique hash that identifies it among all other commits.</li>
<li>Changes are usually introducing or removing lines from a file, deleting a file, or renaming a file.</li>
</ul>
<h2 id="how-do-i-see-the-history">How do I see the history?</h2>
<p>Use <code class="language-plaintext highlighter-rouge">git log <branch> <files></code> to see a list of commits on <code class="language-plaintext highlighter-rouge">branch</code> that edited <code class="language-plaintext highlighter-rouge">files</code> (or any files, if absent).</p>
<h2 id="the-git-workflow">The git workflow</h2>
<ol>
<li>Working set
<ul>
<li>The <em>working set</em> is the state of the files as they are on your machine, right now.</li>
<li>When you make changes, you are editing the working set, making those files <em>modified</em>.</li>
</ul>
</li>
<li>Staging area
<ul>
<li>The <em>staging area</em> (also called the index) is for files that you have finished editing and want to commit the next time <code class="language-plaintext highlighter-rouge">git commit</code> is run.</li>
<li>A file can be both <em>staged</em> and <em>modified</em> if you change it after staging via the <code class="language-plaintext highlighter-rouge">git add</code> command. Simply stage it again to update the staging area.</li>
</ul>
</li>
<li>Committed files
<ul>
<li>Within <code class="language-plaintext highlighter-rouge">.git</code> directory, git holds data structures that describe what it currently believes the file should look like.</li>
<li>You diverge from this state when editing, but then tell git about the changes by <em>committing</em>.</li>
<li><code class="language-plaintext highlighter-rouge">HEAD</code> is a special tag that indicates the commit the index currently represents.
Most of the time this points to a branch, but can potentially not be pointing at a branch (see below).</li>
</ul>
</li>
</ol>
<h3 id="moving-inside-the-workflow">Moving inside the workflow</h3>
<table>
<thead>
<tr>
<th>You want to</th>
<th style="text-align: center">Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>Make your working copy of a file look like how it used to in some past commit (pass <code class="language-plaintext highlighter-rouge">HEAD</code> to essentially drop modified or staged changes)</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git checkout <commit-hash> <files></code></td>
</tr>
<tr>
<td>Reset the working copy and <code class="language-plaintext highlighter-rouge">HEAD</code> to this commit, retaining files changed since that commit in <em>modified</em> state</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git reset <commit-hash></code></td>
</tr>
<tr>
<td>Reset the working copy and <code class="language-plaintext highlighter-rouge">HEAD</code> to a prior commit, <strong>PERMANENTLY ERASING ALL CHANGES SINCE THAT COMMIT</strong> (this is useful if you want to drop all modified and staged files versus the last commit by resetting to <code class="language-plaintext highlighter-rouge">HEAD</code> itself, but otherwise you should <strong>NOT</strong> run this willy-nilly. Ask someone experienced before you do this.)</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git reset --hard <commit-hash></code></td>
</tr>
<tr>
<td>Reset the working copy and <code class="language-plaintext highlighter-rouge">HEAD</code> to a prior commit, allowing you explore the repo as it was at this point in time. This is <em>detached HEAD</em> mode, meaning <code class="language-plaintext highlighter-rouge">HEAD</code> is not pointing to the latest commit of a branch. Thus, do not make changes. Create a branch off of the commit if you need an actual working copy.</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git checkout <commit-hash></code></td>
</tr>
<tr>
<td>Reset the working copy and <code class="language-plaintext highlighter-rouge">HEAD</code> to the latest commit of a branch</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git checkout <branch></code></td>
</tr>
<tr>
<td>Stage a file</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git add <files></code></td>
</tr>
<tr>
<td>Unstage a staged file</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git reset HEAD <files></code> (note how this is a special case of reset above)</td>
</tr>
<tr>
<td>Commit all staged files</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git commit -m <Message></code> (please use commit messages)</td>
</tr>
</tbody>
</table>
<h3 id="working-with-remote-servers">Working with remote servers</h3>
<table>
<thead>
<tr>
<th>You want to</th>
<th style="text-align: center">Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>Copy a remote git repo to your computer, setting <code class="language-plaintext highlighter-rouge">repo-url</code> to the remote name <code class="language-plaintext highlighter-rouge">origin</code></td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git clone <repo-url></code></td>
</tr>
<tr>
<td>Make your local git aware of branches on the server, and their states. Use this to “refresh” a repo (note this does not change your local branches, but simply makes you aware of if yours are outdated or not)</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git fetch <remote-name></code></td>
</tr>
<tr>
<td>Same, but delete all local branches that have since been deleted on the remote</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git fetch <remote-name> --prune</code></td>
</tr>
<tr>
<td>Update a remote branch that doesn’t exist or is directly behind yours</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git push <remote-name> <branch-name></code></td>
</tr>
<tr>
<td>Update your local branch with commits the remote branch has but yours does not</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git pull <remote-name> <branch-name></code> (this may cause merge conflicts!)</td>
</tr>
<tr>
<td>Delete a remote branch</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git push <remote-name> :<branch-name></code></td>
</tr>
</tbody>
</table>
<h3 id="branching">Branching</h3>
<table>
<thead>
<tr>
<th>You want to</th>
<th style="text-align: center">Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>Make fork of the commit tree at your current HEAD. This could be any commit, so you could theoretically go back to an old commit and branch off that.</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git checkout -b <new-branch-name></code></td>
</tr>
<tr>
<td>Switch to an existing branch</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git checkout <branch-name></code></td>
</tr>
<tr>
<td>Delete a branch locally</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git branch -d <branch-name></code></td>
</tr>
<tr>
<td>Force-delete an unmerged branch locally (has commits that will be lost by the delete)</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git branch -D <branch-name></code></td>
</tr>
<tr>
<td>Show all branches</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git branch</code></td>
</tr>
<tr>
<td>Show all branches including remote</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git branch -r</code></td>
</tr>
<tr>
<td>Combine a branch with the current one, merging its commit tree directly into the current one</td>
<td style="text-align: center"><code class="language-plaintext highlighter-rouge">git merge <branch-name></code></td>
</tr>
</tbody>
</table>
<h3 id="working-with-others">Working with others</h3>
<p>Say we are on branch <code class="language-plaintext highlighter-rouge">main</code>. Alice makes some changes to <code class="language-plaintext highlighter-rouge">foo.txt</code>, and commits it. Bob makes some changes to the file and commits as well.
One of them will push first, then the other will then have to pull and then push.</p>
<p>There are two scenarios:</p>
<ul>
<li>Alice and Bob edited completely separate parts of the file.
<ul>
<li>Recall that commits are simply recordings of what’s <em>changed</em> (diffs). If the two commit do not overlap, then it will cleanly be pulled and then the push will succeed.</li>
</ul>
</li>
<li>Alice and Bob edited the same region
<ul>
<li>On pull, we enter what is called a <strong>merge conflict state</strong>. The affected file will gain some markers to guide you to the problem and how to fix it.</li>
</ul>
</li>
</ul>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>This is sentence 1.
This is sentence 2.
<<<<<<< HEAD
This is the awesome and stupendous sentence 3.
=======
This is the amazing and glorious sentence 3.
>>>>>>> <remote>/<branch>
This is sentence 4.
</code></pre></div></div>
<p>If you are the person who has not pushed, you will need to look <strong>carefully</strong> at what is different. Your version is bounded by <code class="language-plaintext highlighter-rouge"><<<<<<</code> and <code class="language-plaintext highlighter-rouge">======</code>, their version is bounded by <code class="language-plaintext highlighter-rouge">=======</code> and <code class="language-plaintext highlighter-rouge">>>>>>></code>. Do <strong>not</strong> just delete one side or the other blindly, you are erasing someone’s changes!</p>
<p>You must consider, <em>semantically</em>, what the other person has changed, then incorporate both of your changes together into one copy. This will often involve discussing the work with the other person. A resolved version of the above example would be as follows:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>This is sentence 1.
This is sentence 2.
This is the awesome, stupendous, amazing and glorious sentence 3.
This is sentence 4.
</code></pre></div></div>
<p>Then, you must stage and commit the fixed file. Finally, push it.</p>
<h2 id="tips">Tips</h2>
<ul>
<li>Often you’ll find yourself switching back and forth between <strong>branchA</strong> and <strong>branchB</strong>. Rather than typing <code class="language-plaintext highlighter-rouge">git checkout branchA</code>, you can use the common command line dash (-) argument to indicate to return to the previous branch, i.e. <code class="language-plaintext highlighter-rouge">git checkout -</code>. This tip works with <code class="language-plaintext highlighter-rouge">git merge</code> as well.</li>
<li>In order to add all changes in a directory, you only need to <code class="language-plaintext highlighter-rouge">git add <dirname></code> for that directory. For the current directory, use <code class="language-plaintext highlighter-rouge">git add .</code>. Note that directory adds are recursive and might include many more files or changes than you intend.</li>
<li>To quickly make a change unrelated to current changes in your local environment you can <code class="language-plaintext highlighter-rouge">git stash</code> your current changes. This basically sets your local changes aside while you do the quick work. After committing the other changes, you can run <code class="language-plaintext highlighter-rouge">git stash pop</code> to get your stashed changes back.</li>
<li><code class="language-plaintext highlighter-rouge">git status</code>. This will tell you what changes are on your system, what is staged for commit, etc. Any time you are in doubt about the current state of your working set, run this command.</li>
<li><code class="language-plaintext highlighter-rouge">git diff</code>. This will show what is different between what is staged (or HEAD if nothing is staged) and the current state of your machine. This is another powerful tool prior to commit to make sure you aren’t committing sensitive information or debug statements.</li>
</ul>Steve BitnerThis primer introduces the basic commands and workflows in the Git™ Version Control System (VCS). For a more detailed look at the workings of Git, refer to the free resource hosted as part of the Git open-source project - git scm book.*nix Plumbing2021-10-08T00:00:00-05:002021-10-08T00:00:00-05:00https://stevenbitner.github.io/posts/plumbing<p>Unix-based systems generally have a similar command line interface (CLI).
This interface is challenging at first, but allows users to do powerful operations in a fraction of the time required to do the same task in a GUI.
An additional benefit is that actions are more repeatable via the CLI.
One useful thing to do is chain together multiple commands into one mega-command.
This chaining is accomplished with the pipe key <code class="language-plaintext highlighter-rouge">|</code>.
Since pipes are used to connect commands, this is colloquially referred to as “plumbing”.</p>
<h2 id="simple-use-case">Simple use case</h2>
<p>Want to know what processes are running using vim?
Run <code class="language-plaintext highlighter-rouge">ps aux | grep vim</code>.
This will print out all processes (<code class="language-plaintext highlighter-rouge">ps aux</code>) and filter them through the search (grep) command with the search term “vim”.</p>
<h2 id="keyboard-input">Keyboard input</h2>
<p>While developing or debugging a terminal program it is important to enter in text via the keyboard.
If your input changes (by accident), you might mistakenly think that you fixed (or didn’t fix) the bug.
It is also common to need to enter a lot of info, which can be time consuming and is likely to convince you to develop too much code in one step.
However, if you place the inputs you would type into a text file, you can simply override the standard keyboard input with the contents of that teext file.
For example <code class="language-plaintext highlighter-rouge">cat my-inputs.txt | ./a.out</code> would run the a.out program and use the contents of my-inputs.txt just as if you typed it all in after starting the program.</p>
<p>For this input text file</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>12
Hey-o
</code></pre></div></div>
<p>and the following cpp file compiled as a.out</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include <iostream>
#include <string>
</span>
<span class="kt">int</span> <span class="nf">main</span> <span class="p">()</span>
<span class="p">{</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"Enter an integer value for Foo: "</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">foo</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">cin</span> <span class="o">>></span> <span class="n">foo</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"Foo was: "</span> <span class="o"><<</span> <span class="n">foo</span> <span class="o"><<</span> <span class="sc">'\n'</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"Enter a string value for bar: "</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">bar</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">cin</span> <span class="o">>></span> <span class="n">bar</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"Bar was: "</span> <span class="o"><<</span> <span class="n">bar</span> <span class="o"><<</span> <span class="sc">'\n'</span><span class="p">;</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>would output</p>
<blockquote>
<p>Enter an integer value for Foo:<br />
Enter a string value for bar:<br />
Foo was: 12<br />
Bar was: Hey-o</p>
</blockquote>
<p>This simple input file might not convince you of the power of this approach, but if your program requires a lot of input, or just input that is challenging to type exactly right, the benefit is substantial.</p>
<h2 id="questions">Questions?</h2>
<p>I hope this helps clear some things up.
If you have questions, ask Google or StackOverflow.
If you are my student, come on by my office hours or message me in Discord and we’ll get it figured out together.</p>Steve BitnerUnix-based systems generally have a similar command line interface (CLI). This interface is challenging at first, but allows users to do powerful operations in a fraction of the time required to do the same task in a GUI. An additional benefit is that actions are more repeatable via the CLI. One useful thing to do is chain together multiple commands into one mega-command. This chaining is accomplished with the pipe key |. Since pipes are used to connect commands, this is colloquially referred to as “plumbing”.Simplifying Make2021-09-02T00:00:00-05:002021-09-02T00:00:00-05:00https://stevenbitner.github.io/posts/make<p>This is an attempt at simplifying <strong>make</strong>, I hope it can help anyone who struggling with the basics.</p>
<h2 id="simplifying-the-makefile">Simplifying the Makefile</h2>
<p>The simplest form for a Makefile is:</p>
<div class="language-make highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">TARGET</span><span class="o">:</span> <span class="nf">DEPENDENCIES</span>
COMMAND<span class="o">(</span>S<span class="o">)</span>
</code></pre></div></div>
<p>So, if you want to do some command or commands, give it a name (TARGET) and if the commands are dependent upon anything, list those dependencies.
For example, if I wanted to compile a simple <strong>main.cpp</strong> file the command would be <code class="language-plaintext highlighter-rouge">g++ main.cpp</code>.
I can name that command whatever I want, possibly snuka (my dog’s name).
The main file in this example doesn’t require files other than itself, so the dependency list would simply be itself.</p>
<div class="language-make highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">snuka</span><span class="o">:</span> <span class="nf">main.cpp</span>
g++ main.cpp
</code></pre></div></div>
<p>If that main file used a class I developed, such as <strong><em>Dog</em></strong>, defined in <strong>dog.cpp</strong> and <strong>dog.hpp</strong>, then my main program will depend on that class.
Classes are most easily dealt with when compiled into object files such as <strong>dog.o</strong>.
Make will create the <strong>dog.o</strong> file automatically (or at least try to), if I need it.
So now my rule might need to be:</p>
<div class="language-make highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">snuka</span><span class="o">:</span> <span class="nf">main.cpp dog.o</span>
g++ main.cpp dog.o
</code></pre></div></div>
<p>If I wanted to name the executable snuka, rather than a.out (the default), the rule would be:</p>
<div class="language-make highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">snuka</span><span class="o">:</span> <span class="nf">main.cpp dog.o</span>
g++ main.cpp dog.o <span class="nt">-o</span> snuka
</code></pre></div></div>
<p>Thus, to build an executable file named <strong>snuka</strong>, which has a <code class="language-plaintext highlighter-rouge">main</code> function in <strong>main.cpp</strong> and uses code from the <code class="language-plaintext highlighter-rouge">Dog</code> class, I’d just need to run <code class="language-plaintext highlighter-rouge">make snuka</code>.</p>
<h3 id="variables">Variables</h3>
<p>There are a couple of variables that are very helpful in a Makefile.
Firstly, at the top of a Makefile, it’s always useful to define <code class="language-plaintext highlighter-rouge">CXX</code> and <code class="language-plaintext highlighter-rouge">CXXFLAGS</code>.
These are the compiler command (<code class="language-plaintext highlighter-rouge">CXX</code>) and the flags (<code class="language-plaintext highlighter-rouge">CXXFLAGS</code>) to the compiler that will be used by <strong>make</strong> for all <em>implicit</em> rules.
Above, we didn’t create a rule for the <strong>dog.o</strong> file.
The <strong>make</strong> program <em>guessed</em> how to create the .o file.
It’s generally pretty good at doing that when a .hpp and .cpp file exist with the same name.
It will use the <code class="language-plaintext highlighter-rouge">CXX</code> compile command and pass the <code class="language-plaintext highlighter-rouge">CXXFLAGS</code> when it does that.
If you didn’t define those then it will use system defaults.</p>
<p>If you just want to make a rule a bit cleaner and more portable, you can use automatic variables in your rules.
The dollar sign (<code class="language-plaintext highlighter-rouge">$</code>) is used to de-reference variables, i.e. get their values, and you can think of them as a replacement.
If you define <code class="language-plaintext highlighter-rouge">CXXFLAGS = -std=c++17 -Wall</code>, then whenever you put <code class="language-plaintext highlighter-rouge">$(CXXFLAGS)</code> in your Makefile, it’ll be replaced by <code class="language-plaintext highlighter-rouge">-std=c++17 -Wall</code> when you run <strong>make</strong>.</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">$@</code> - this <em>at</em> variable refers to the name of the rule. Above, <code class="language-plaintext highlighter-rouge">$@</code> would be <strong>snuka</strong>.</li>
<li><code class="language-plaintext highlighter-rouge">$^</code> - this can be used to avoid retyping all of the dependencies. It will be replaced by the entire list.</li>
</ul>
<p>So, with those variables available, our <strong>snuka</strong> rule could be written as:</p>
<div class="language-make highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">snuka</span><span class="o">:</span> <span class="nf">main.cpp dog.o</span>
g++ <span class="nv">$^</span> <span class="nt">-o</span> <span class="nv">$@</span>
</code></pre></div></div>
<p>or if we want to use the specific flags and compiler,</p>
<div class="language-make highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">snuka</span><span class="o">:</span> <span class="nf">main.cpp dog.o</span>
<span class="nv">$(CXX)</span> <span class="nv">$(CXXFLAGS)</span> <span class="nv">$^</span> <span class="nt">-o</span> <span class="nv">$@</span>
</code></pre></div></div>
<p>It might look a bit scary at first, but it’s a very simple syntax to get used to after you play with it a bit.</p>
<h2 id="questions">Questions?</h2>
<p>I hope this helps clear some things up.
If you have questions, ask Google or StackOverflow.
If you are my student, come on by my office hours or message me in Discord and we’ll get it figured out together.</p>Steve BitnerThis is an attempt at simplifying make, I hope it can help anyone who struggling with the basics.Basic Vim Setup2021-01-18T00:00:00-06:002021-01-18T00:00:00-06:00https://stevenbitner.github.io/posts/basic-vim-setup<p>Vim is by no means the only code editing tool out there…it’s just the best one <g-emoji class="g-emoji" alias="grin" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f601.png">😁</g-emoji>.
It is highly customizable, and if you choose it as your editor you will modify it over time to suit your needs.
For beginners, a very simple setup can go a long way in helping to develop code.</p>
<p><img src="/images/error-tray.png" alt="Display of syntax error feedback in Vim" /></p>
<h2 id="tldr">TL/DR</h2>
<p>Don’t want to read?
Copy/paste the following block in your terminal, if it works (and you don’t care why), no need to read on.</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">mkdir</span> <span class="nt">-p</span> ~/.vim/autoload ~/.vim/bundle <span class="o">&&</span> <span class="se">\</span>
curl <span class="nt">-LSso</span> ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim <span class="o">&&</span> <span class="se">\</span>
<span class="nb">printf</span> <span class="s1">'%s\n'</span> <span class="s1">''</span> <span class="s1">'"Plugin manager'</span> <span class="s1">'execute pathogen#infect()'</span> <span class="se">\</span>
<span class="s1">'"Syntax help'</span> <span class="s1">'syntax on'</span> <span class="s1">'filetype plugin indent on'</span> <span class="s1">''</span> <span class="se">\</span>
<span class="s1">'let g:syntastic_cpp_check_header = 1'</span> <span class="s1">'let g:syntastic_auto_loc_list = 1'</span> <span class="se">\</span>
<span class="s1">'let g:syntastic_always_populate_loc_list = 1'</span> <span class="se">\</span>
<span class="s1">'let g:syntastic_check_on_open = 1'</span> <span class="s1">'let g:syntastic_check_on_wq = 0'</span> <span class="s1">''</span> <span class="o">>></span> ~/.vimrc <span class="o">&&</span> <span class="se">\</span>
git clone <span class="nt">--depth</span><span class="o">=</span>1 https://github.com/vim-syntastic/syntastic.git ~/.vim/bundle/syntastic
</code></pre></div></div>
<hr />
<h2 id="pathogen">Pathogen</h2>
<p>Like most complex text editors, Vim allows enhancements through plugins.
Pathogen is a great tool that automatically loads all plugins in the ~/.vim/bundle directory.</p>
<h3 id="install-pathogen">Install Pathogen</h3>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">mkdir</span> <span class="nt">-p</span> ~/.vim/autoload ~/.vim/bundle <span class="o">&&</span> <span class="se">\</span>
curl <span class="nt">-LSso</span> ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim
</code></pre></div></div>
<p><strong>If you’re using Windows <em>(not applicable if using Ubuntu or other Linux systems inside Windows)</em>, change all occurrences of ~/.vim to ~\vimfiles</strong></p>
<h2 id="vimrc">~/.vimrc</h2>
<p>This is the configuration file for Vim and is likely to grow a lot over time if you use Vim a lot.
Add pathogen loading to your vim config file.
If you aren’t sure how to do that, running this command will add the necessary content to your config</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">printf</span> <span class="s1">'%s\n'</span> <span class="s1">''</span> <span class="s1">'"Plugin manager'</span> <span class="s1">'execute pathogen#infect()'</span> <span class="se">\</span>
<span class="s1">'"Syntax help'</span> <span class="s1">'syntax on'</span> <span class="s1">'filetype plugin indent on'</span> <span class="s1">''</span> <span class="se">\</span>
<span class="s1">'let g:syntastic_cpp_check_header = 1'</span> <span class="s1">'let g:syntastic_auto_loc_list = 1'</span> <span class="se">\</span>
<span class="s1">'let g:syntastic_always_populate_loc_list = 1'</span> <span class="se">\</span>
<span class="s1">'let g:syntastic_check_on_open = 1'</span> <span class="s1">'let g:syntastic_check_on_wq = 0'</span> <span class="s1">''</span> <span class="o">>></span> ~/.vimrc <span class="o">&&</span> <span class="se">\</span>
<span class="o">>></span> ~/.vimrc
</code></pre></div></div>
<h2 id="syntastic">Syntastic</h2>
<p>Syntastic is a syntax static checker that will check for syntax errors when you save a file.
To <em>install</em> Syntastic, just run</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git clone <span class="nt">--depth</span><span class="o">=</span>1 https://github.com/vim-syntastic/syntastic.git ~/.vim/bundle/syntastic
</code></pre></div></div>
<p>That’s it.
Pathogen will handle the loading of the plugin for you and nothing more should be needed.
The README files for both Pathogen and Syntastic have other options that you might be interested in, but this should get you up and running.</p>Steve BitnerVim is by no means the only code editing tool out there…it’s just the best one 😁. It is highly customizable, and if you choose it as your editor you will modify it over time to suit your needs. For beginners, a very simple setup can go a long way in helping to develop code.Debugging Segmentation Faults in C++2020-10-01T00:00:00-05:002020-10-01T00:00:00-05:00https://stevenbitner.github.io/posts/cpp-debugging-seg-faults<p>Segmentation faults in C++ are a sign that you are trying to do hard things.
Congratulations!
Now, let’s take a peek at how to start debugging.</p>
<p><img src="https://media.giphy.com/media/xT5LMYqgQk7yAhvvRm/giphy.gif" alt="Homer Simpson Y2K joke" /></p>
<h2 id="valgrind">Valgrind</h2>
<p>Never underestimate the easiest option.
If trying to run <code class="language-plaintext highlighter-rouge">a.out</code> results in a seg fault, try running it through Valgrind to see if you can gain some insight.</p>
<p><code class="language-plaintext highlighter-rouge">./a.out</code></p>
<blockquote>
<p>Segmentation fault: 11</p>
</blockquote>
<p><code class="language-plaintext highlighter-rouge">valgrind ./a.out</code></p>
<blockquote>
<p>==57489== Memcheck, a memory error detector<br />
==57489== Copyright (C) 2002-2017, and GNU GPL’d, by Julian Seward et al.<br />
==57489== Using Valgrind-3.16.0.GIT and LibVEX; rerun with -h for copyright info<br />
==57489== Command: ./a.out<br />
==57489== <br />
–57489– run: /usr/bin/dsymutil “./a.out”<br />
warning: no debug symbols in executable (-arch x86_64)<br />
0 1 2 3 4 5 <br />
==57489== <strong>Invalid read of size 4</strong><br />
==57489== at 0x100003C5B: operator«(std::ostream&, SimpleGrid const&) (in ./a.out)<br />
==57489== by 0x100003933: main (in ./a.out)<br />
==57489== Address 0x1200000002 is not stack’d, malloc’d or (recently) free’d<br />
==57489== <br />
==57489== <br />
==57489== Process terminating with default action of signal 11 (SIGSEGV)<br />
==57489== <strong>Access not within mapped region at address 0x1200000002</strong><br />
==57489== at 0x100003C5B: operator«(std::ostream&, SimpleGrid const&) (in ./a.out)<br />
==57489== by 0x100003933: main (in ./a.out)<br />
==57489== If you believe this happened as a result of a stack<br />
==57489== overflow in your program’s main thread (unlikely but<br />
==57489== possible), you can try to increase the size of the<br />
==57489== main thread stack using the –main-stacksize= flag.<br />
==57489== The main thread stack size used in this run was 8388608.<br />
==57489== <br />
==57489== HEAP SUMMARY:<br />
==57489== in use at exit: 90,922 bytes in 164 blocks<br />
==57489== total heap usage: 178 allocs, 14 frees, 95,666 bytes allocated<br />
==57489== <br />
==57489== LEAK SUMMARY:<br />
==57489== definitely lost: 0 bytes in 0 blocks<br />
==57489== indirectly lost: 0 bytes in 0 blocks<br />
==57489== possibly lost: 4,392 bytes in 5 blocks<br />
==57489== still reachable: 86,530 bytes in 159 blocks<br />
==57489== suppressed: 0 bytes in 0 blocks<br />
==57489== Rerun with –leak-check=full to see details of leaked memory<br />
==57489== <br />
==57489== For lists of detected and suppressed errors, rerun with: -s<br />
==57489== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 1 from 1)<br />
Segmentation fault: 11</p>
</blockquote>
<p>Bold font added above for instructive purposes.
This Valgrind output indicates that my program is trying to access something outside a mapped region.
This almost certainly comes from defining an array of size <strong>n</strong> and trying to access element <strong>n+1</strong> which would be index <strong>n</strong>.
So, in just a second or two, we know to check our array bounds, most likely due to an improperly defined <code class="language-plaintext highlighter-rouge">for</code> loop.</p>
<p><strong>For a bit more insight, recompile your program with the <code class="language-plaintext highlighter-rouge">-g</code> flag and you’ll probably get the line number where the violation occurred.</strong></p>
<h2 id="gdb">GDB</h2>
<p>GDB is a powerful debugger that allows a programmer to step through their code line by line and probe any variable for its value at that step of execution.
It has a lot of capability beyond what can be addressed in a simple primer.
A very useful cheat sheet that I always have a printed copy of on my desk can be found here <a href="https://darkdust.net/files/GDB%20Cheat%20Sheet.pdf">https://darkdust.net/files/GDB Cheat Sheet.pdf</a>.</p>
<p>First and foremost, GDB will need some specific information injected into the executable that needs to be debugged.
This requires compiling all of our code with the <code class="language-plaintext highlighter-rouge">-g</code> flag.
The best way to do this is by adding it to your <code class="language-plaintext highlighter-rouge">CXXFLAGS</code> variable in your Makefile.
That ensures that all automatically created *.o files are also built using the <code class="language-plaintext highlighter-rouge">-g</code> flag.
You should also delete the old *.o files before rebuilding.
This is a great time to run <code class="language-plaintext highlighter-rouge">make clean</code>, assuming you have a well-defined <code class="language-plaintext highlighter-rouge">clean</code> rule in your Makefile.</p>
<p>Now that you have recompiled with <code class="language-plaintext highlighter-rouge">-g</code> flags, you can fire up the debugger.
The <code class="language-plaintext highlighter-rouge">-tui</code> flag below opens the source code in the top half of the screen which is great for adding some context to where the program is in the execution.
<code class="language-plaintext highlighter-rouge">gdb -tui a.out</code></p>
<p>If files were built with <code class="language-plaintext highlighter-rouge">-g</code>, the symbol table should load and GDB is ready to use.
The first thing that is typically needed is to add one or more breakpoints.
These can be added to method names, or to lines of code (if you specify a line that cannot break, the next breakable line is used).</p>
<h3 id="breaking-on-a-specific-line-of-source-code">Breaking on a specific line of source code</h3>
<p>To halt execution at line 12 of test.cpp, you would simply type <code class="language-plaintext highlighter-rouge">break test.cpp:12</code>.
Now when you type <code class="language-plaintext highlighter-rouge">run</code>, GDB starts executing and will halt at line 12 (or the next breakable line) so that you can inspect the status of your program.</p>
<h3 id="breaking-on-a-method">Breaking on a method</h3>
<p>If you suspect a specific method or function in your code, you can halt execution and inspect whenever that method is called.
In order to inspect the method <code class="language-plaintext highlighter-rouge">Search</code> within the <code class="language-plaintext highlighter-rouge">BinarySearch</code> class, I would type <code class="language-plaintext highlighter-rouge">break BinarySearch::Search(int*, int, int, int)</code>.
As you might have guessed, this is a great time for tab-completion which GDB is great at.
Just start typing the class or method name and hit <strong>tab</strong> in order to fill in the rest.
Now when you type <code class="language-plaintext highlighter-rouge">run</code>, GDB starts executing and will halt the first (and every) time that method is called.</p>
<h3 id="stepping-through">Stepping through</h3>
<p>The commands needed to restart execution after a breakpoint has been reached are:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">next</code> - This goes to the next line of code, but will not dive into functions.</li>
<li><code class="language-plaintext highlighter-rouge">step</code> - This goes to the next line of instruction. This might be inside of a function call or elsewhere in the code tree.</li>
<li><code class="language-plaintext highlighter-rouge">continue</code> - This runs the program until the end of execution, or until a breakpoint is reached.</li>
</ul>
<h3 id="looking-at-values">Looking at values</h3>
<p>The simple act of stepping through code often helps figure out the problem.
“This should not go inside that <code class="language-plaintext highlighter-rouge">if</code> statement”…well, it does, so figure out why.</p>
<p>Sometimes, it is not enough to just know the current location of your code execution.
Luckily, we can print out values of our variables.
<code class="language-plaintext highlighter-rouge">print myVar</code> would print the value of <code class="language-plaintext highlighter-rouge">myVar</code>.
<code class="language-plaintext highlighter-rouge">print &myVar</code> would print the address of <code class="language-plaintext highlighter-rouge">myVar</code>.
Pointers will print the address by default.
To see their value, you would need to dereference, e.g. <code class="language-plaintext highlighter-rouge">print *myPointer</code>.
As you might have noticed, the print statement is identical to sticking in <code class="language-plaintext highlighter-rouge">std::cout</code> statements, except that you don’t need to guess in advance, you can <em>poke around</em> until you find the values you need.
Print will also let you call methods, so <code class="language-plaintext highlighter-rouge">print myObject.GetSomeData()</code> would print the results of the method call.</p>
<p>When breaking on a method call, the arguments passed to the call are printed automatically.
For the BinarySearch breakpoint we mentioned earlier, when the breakpoint is triggered, the output might read:</p>
<blockquote>
<p>Breakpoint 1, BinarySearch::Search (listOfNumbers=0x7fffffffc720, left=7, right=10, searchKey=10) at binary-search.cpp:5</p>
</blockquote>
<h2 id="stdcout"><code class="language-plaintext highlighter-rouge">std::cout</code></h2>
<p>“Did this line run?”
You can always try sending output to screen in a bunch of places to approximate the power you can get via step-through debugging with a tool such as <a href="#gdb">gdb</a>.
If you have peppered more than a couple such statements in your code for the purpose of tracking down a single bug, you’re likely to be better off just using GDB.
If you have a bunch of output statements in your code as a standard part of your development process, you are almost certainly missing out on the real power of unit tests and TDD in particular.</p>
<p>Depending on where your output statements are, and where the seg fault occurs, it is possible that output is still in the buffer when the crash occurs.
This can be misleading since you won’t see the output and might think the error must have occurred first.
To flush the buffer you can add the <code class="language-plaintext highlighter-rouge">std::endl</code> output sequence to your <code class="language-plaintext highlighter-rouge">cout</code>s.
This should ensure that the output that gets generated does indeed make it to your screen rather than dying on the way.
So, replace output such as</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"Foo value: "</span> <span class="o"><<</span> <span class="n">foo</span> <span class="o"><<</span> <span class="sc">'\n'</span><span class="p">;</span>
</code></pre></div></div>
<p>with</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"Foo value: "</span> <span class="o"><<</span> <span class="n">foo</span> <span class="o"><<</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
</code></pre></div></div>
<h2 id="commenting-out-code">Commenting Out Code</h2>
<p>The “<em>old reliable</em>”, never forget that a program with zero lines of code doesn’t have any seg faults.
Commenting out blocks of code can sometimes be a very useful strategy to narrowing down the location of a bug.
Lines 100-200 are commented out but you still have the seg fault, it must be someplace else.</p>
<p>When using this approach, don’t forget about the power of binary search.
Searching for a seg fault in 100 lines of code shouldn’t require “toggling” smaller and smaller blocks of code on and off more than a handful of times.</p>
<h2 id="comparison">Comparison</h2>
<table>
<thead>
<tr>
<th style="text-align: left">Tool</th>
<th style="text-align: center">Does not require recompiling</th>
<th style="text-align: center">Fast</th>
<th style="text-align: center">Easy to use</th>
<th style="text-align: center">Easy to understand</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">Valgrind</td>
<td style="text-align: center">X</td>
<td style="text-align: center">X</td>
<td style="text-align: center">X</td>
<td style="text-align: center"> </td>
</tr>
<tr>
<td style="text-align: left">GDB</td>
<td style="text-align: center"> </td>
<td style="text-align: center"> </td>
<td style="text-align: center"> </td>
<td style="text-align: center">X</td>
</tr>
<tr>
<td style="text-align: left"><code class="language-plaintext highlighter-rouge">std::cout</code></td>
<td style="text-align: center"> </td>
<td style="text-align: center">If you get lucky</td>
<td style="text-align: center">X</td>
<td style="text-align: center">X</td>
</tr>
<tr>
<td style="text-align: left">Commenting</td>
<td style="text-align: center"> </td>
<td style="text-align: center">X</td>
<td style="text-align: center">X</td>
<td style="text-align: center">X</td>
</tr>
</tbody>
</table>Steve BitnerSegmentation faults in C++ are a sign that you are trying to do hard things. Congratulations! Now, let’s take a peek at how to start debugging.Common Constructor Mistakes in C++2019-09-20T00:00:00-05:002019-09-20T00:00:00-05:00https://stevenbitner.github.io/posts/cpp-constructor-gotchas<p>It is very common to have some difficulty when constructing custom classes in C++.
Below I’ll discuss what tend to be the two most common problems I see with student submissions.
The first is local scope vs instance variables.
The second is a lack of default constructors.</p>
<h2 id="scope">Scope</h2>
<p><img src="/images/im-local.jpg" alt="Don't Hassle Me, I'm Local shirt from What About Bob" /></p>
<p>A very common issue comes from forgetting about the concept of variable scope in C++.
Any time we call a function (and a constructor is just a function, after all) we can declare local variables inside that function.
For example:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">int</span> <span class="n">Foo</span><span class="o">::</span><span class="n">MyCoolFunction</span> <span class="p">(</span><span class="kt">double</span> <span class="n">importantData</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">nameOfCoolStuff</span> <span class="o">=</span> <span class="s">"me, probably"</span><span class="p">;</span>
<span class="n">instanceData</span> <span class="o">=</span> <span class="n">importantData</span><span class="p">;</span> <span class="c1">// instance data, should use this-></span>
<span class="n">importantData</span> <span class="o">+=</span> <span class="mf">1.37</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>The code block above does a few things.</p>
<ul>
<li>It declares a locally-scoped variable named <code class="language-plaintext highlighter-rouge">importantData</code> (this happens in the function declaration).</li>
<li>It declares another locally-scoped variable named <code class="language-plaintext highlighter-rouge">nameOfCoolStuff</code>.</li>
<li>It assigns the value passed in to the function to an instance variable called <code class="language-plaintext highlighter-rouge">instanceData</code>.
After that, we make some change to <code class="language-plaintext highlighter-rouge">importantData</code>.
Then the function ends.
That final change did nothing since the variable is local and goes out of scope at the closing brace.</li>
</ul>
<p><strong>Note that setting instance data should be done by prefixing with <code class="language-plaintext highlighter-rouge">this-></code> for clarity.</strong>
It isn’t necessary (from the compiler’s perspective) to prepend <code class="language-plaintext highlighter-rouge">this-></code> as long as no local variable has the same name.
This confusion is so easy to avoid with just a few keystrokes.
Get in the habit.</p>
<p>The same applies when the instance variable you wish to set is an object.
The first line in this function declares a locally-scoped variable which gets deleted at the conclusion of the function…typically not what is desired in a constructor.</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Myclass</span> <span class="p">()</span>
<span class="p">{</span>
<span class="n">MyOtherClass</span> <span class="n">reallyImportantStuff</span><span class="p">(</span><span class="mi">7</span><span class="p">);</span> <span class="c1">// local scope</span>
<span class="k">this</span><span class="o">-></span><span class="n">instanceObject</span> <span class="o">=</span> <span class="n">MyOtherClass</span><span class="p">(</span><span class="mi">12</span><span class="p">);</span> <span class="c1">// available outside constructor</span>
<span class="p">}</span>
</code></pre></div></div>
<p>If you put the variable type in front of the variable name, you are <strong>declaring</strong> a variable.
That variable will have a local scope and is lost upon completion of the constructor function.</p>
<h2 id="initialization-list">Initialization List</h2>
<p>If one class contains another class, you might run into issues if no default constructor exists for the <em>contained</em> class instance.
This is because of how C++ calls constructors.
When a constructor is called, in initializes all instance variables <strong>before</strong> starting the execution of the constructor body.
If a class contains another class, it will initialize the variable by using a default constructor.
This is not an issue if a default constructor exists, but if one does not your code will not compile.</p>
<blockquote>
<p>bar.cpp|9 col 3 error| constructor for ‘Bar’ must explicitly initialize the member ‘myFoo’ which does not have a default constructor</p>
</blockquote>
<blockquote>
<p>bar.cpp|6 col 7 error| note: member is declared here</p>
</blockquote>
<blockquote>
<p>foo.cpp|1 col 7 error| note: ‘Foo’ declared here</p>
</blockquote>
<p><em><strong>foo.cpp</strong></em></p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Foo</span>
<span class="p">{</span>
<span class="nl">private:</span>
<span class="kt">int</span> <span class="n">value</span><span class="p">;</span>
<span class="nl">public:</span>
<span class="n">Foo</span> <span class="p">(</span><span class="kt">int</span> <span class="n">value</span><span class="p">)</span> <span class="p">{</span> <span class="k">this</span><span class="o">-></span><span class="n">value</span> <span class="o">=</span> <span class="n">value</span><span class="p">;</span> <span class="p">}</span>
<span class="p">};</span>
</code></pre></div></div>
<p><em><strong>bar.cpp</strong></em></p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include "foo.cpp"
</span>
<span class="k">class</span> <span class="nc">Bar</span>
<span class="p">{</span>
<span class="nl">private:</span>
<span class="n">Foo</span> <span class="n">myFoo</span><span class="p">;</span>
<span class="nl">public:</span>
<span class="n">Bar</span> <span class="p">()</span>
<span class="p">{</span>
<span class="n">myFoo</span> <span class="o">=</span> <span class="n">Foo</span><span class="p">(</span><span class="mi">12</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">};</span>
</code></pre></div></div>
<p>So, what if you cannot make changes to the class to add a default constructor?
Or perhaps you just don’t think a default constructor makes sense.</p>
<p>Well, if you know the data that you plan to pass to the inner constructor ahead of time, you can use an initialization in your function declaration.
They are quite simple, for example the constructor in <em><strong>bar.cpp</strong></em> above could have been written like this instead:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Bar</span> <span class="p">()</span> <span class="o">:</span> <span class="n">myFoo</span><span class="p">(</span><span class="mi">12</span><span class="p">)</span> <span class="p">{</span> <span class="p">};</span>
</code></pre></div></div>
<p>This initializes <code class="language-plaintext highlighter-rouge">myFoo</code> <em>before</em> the constructor body is executed.
Note that in this trivial example, we no longer need to do anything in the constructor body, thus the function is now empty <code class="language-plaintext highlighter-rouge">{ }</code>.</p>
<p>More than one initialization can be used, just separate them by a comma, e.g.</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Bar</span> <span class="p">()</span> <span class="o">:</span> <span class="n">myFoo</span><span class="p">(</span><span class="mi">12</span><span class="p">),</span> <span class="n">myInt</span><span class="p">(</span><span class="mi">4</span><span class="p">),</span> <span class="n">myString</span><span class="p">(</span><span class="s">"hello world"</span><span class="p">)</span> <span class="p">{</span> <span class="p">};</span>
</code></pre></div></div>
<h2 id="questions">Questions?</h2>
<p>I hope this helps clear some things up.
If you have questions, ask Google or StackOverflow.
If you are my student, come on by my office hours and we’ll get it figured out together.</p>Steve BitnerIt is very common to have some difficulty when constructing custom classes in C++. Below I’ll discuss what tend to be the two most common problems I see with student submissions. The first is local scope vs instance variables. The second is a lack of default constructors.Uninitialized variables in C++2019-09-20T00:00:00-05:002019-09-20T00:00:00-05:00https://stevenbitner.github.io/posts/cpp-uninitialized-variables<p>C++ won’t always work the way you expect, and that is by design.
It’s a remarkably rigid language and it requires that a programmer cross all of their <em>f</em>’s and dot all of their <em>j</em>’s.</p>
<h2 id="undefined-behavior">Undefined Behavior</h2>
<p><img src="/images/schrodingers-cat.jpg" alt="Schrodinger's cat joke" /></p>
<p>For the authoritative reference, see <a href="https://en.cppreference.com/w/c/language/behavior">https://en.cppreference.com/w/c/language/behavior</a>.</p>
<h3 id="when-might-this-happen">When Might This Happen?</h3>
<p>If you declare variables without initializing them, you’ll inevitably have problems.
Some of those problems will immediately cause segmentation faults and lead you down your happy debugging path.
Others can be quiet and might deceive you into thinking that your program works as expected.</p>
<p>Note that not all OSs and not all compilers do the same thing.
The examples below might not give strange results on Mac OS, but then will on Cent OS, or vice-versa.</p>
<h2 id="how-do-i-detect-these-problems">How Do I Detect These Problems?</h2>
<p>The following program will run without error but the behavior is undefined and will differ from system to system.</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include <iostream>
</span>
<span class="kt">int</span> <span class="nf">main</span> <span class="p">()</span>
<span class="p">{</span>
<span class="kt">bool</span> <span class="n">b</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"True</span><span class="se">\n</span><span class="s">"</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">else</span>
<span class="p">{</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"False</span><span class="se">\n</span><span class="s">"</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Compiling your code with the <code class="language-plaintext highlighter-rouge">-Wuninitialized</code> (or <code class="language-plaintext highlighter-rouge">-Wall</code> which will report other warnings as well) flag will detect the use of uninitialized scalar values.</p>
<blockquote>
<p><strong>foo.cpp:</strong> In function <strong><code class="language-plaintext highlighter-rouge">int main()</code></strong>:<br />
<strong>foo.cpp:6:2:</strong> <em>warning:</em> <code class="language-plaintext highlighter-rouge">b</code> is used uninitialized in this function [-Wuninitialized]<br />
if (b)<br />
^<br />
False</p>
</blockquote>
<h3 id="this-wont-work-on-the-hard-stuff">This Won’t Work On the Hard Stuff</h3>
<p>Ask yourself what the following snippet will output.</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">bool</span><span class="o">*</span> <span class="n">uninitializedBool</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">bool</span><span class="p">[</span><span class="mi">10</span><span class="p">];</span> <span class="c1">// uninitialized local variable</span>
<span class="k">if</span> <span class="p">(</span><span class="n">uninitializedBool</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
<span class="p">{</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"true</span><span class="se">\n</span><span class="s">"</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">uninitializedBool</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
<span class="p">{</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"false</span><span class="se">\n</span><span class="s">"</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>If you guessed</p>
<blockquote>
<p>true<br />
false</p>
</blockquote>
<p>you are pretty good.
Whether you guessed that or not, you are likely pretty confused.
How can a variable be both <code class="language-plaintext highlighter-rouge">true</code> and <code class="language-plaintext highlighter-rouge">false</code>?
This is captured by the statement from the cpp resource above as <em>unspecified behavior</em>.
Specifically,</p>
<blockquote>
<p>Each unspecified behavior results in one of a set of valid results and may produce a different result when repeated in the same program.</p>
</blockquote>
<p>Not precisely a Schrodinger’s Cat analog, but close enough to include a funny comic in the intro.</p>
<h2 id="id-never-do-that">I’d Never Do That</h2>
<p>Clearly the example above is trivial for the sake of showing a minimal example.
In reality, this might be forgetting to initialize the final element in an array, or the final dimension in a multi-dimensional array.
Having a <code class="language-plaintext highlighter-rouge">for</code> loop end early, or forgetting to increment an index will land you in this situation.</p>
<h2 id="so-how-do-i-detect-these-problems">So, How <em>Do</em> I Detect These Problems?</h2>
<p>When in doubt, <code class="language-plaintext highlighter-rouge">valgrind</code>.
Running Valgrind on the program produced above would give something along the lines of</p>
<blockquote>
<p>==2766== Memcheck, a memory error detector<br />
==2766== Copyright (C) 2002-2017, and GNU GPL’d, by Julian Seward et al.<br />
==2766== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info<br />
==2766== Command: ./a.out<br />
==2766==<br />
==2766== <strong>Conditional jump or move depends on uninitialised value(s)</strong><br />
==2766== at 0x40074C: main (in /home/sbitner/a.out)<br />
==2766==<br />
==2766== <strong>Conditional jump or move depends on uninitialised value(s)</strong><br />
==2766== at 0x400769: main (in /home/sbitner/a.out)<br />
==2766==<br />
false<br />
==2766==<br />
==2766== HEAP SUMMARY:<br />
==2766== in use at exit: 10 bytes in 1 blocks<br />
==2766== total heap usage: 1 allocs, 0 frees, 10 bytes allocated<br />
==2766==<br />
==2766== LEAK SUMMARY:<br />
==2766== definitely lost: 10 bytes in 1 blocks<br />
==2766== indirectly lost: 0 bytes in 0 blocks<br />
==2766== possibly lost: 0 bytes in 0 blocks<br />
==2766== still reachable: 0 bytes in 0 blocks<br />
==2766== suppressed: 0 bytes in 0 blocks<br />
==2766== Rerun with –leak-check=full to see details of leaked memory<br />
==2766==<br />
==2766== For counts of detected and suppressed errors, rerun with: -v<br />
==2766== Use –track-origins=yes to see where uninitialized values come from<br />
==2766== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)<br /></p>
</blockquote>
<h2 id="questions">Questions?</h2>
<p>I hope this helps clear some things up.
If you have questions, ask Google or StackOverflow.
If you are my student, come on by my office hours and we’ll get it figured out together.</p>Steve BitnerC++ won’t always work the way you expect, and that is by design. It’s a remarkably rigid language and it requires that a programmer cross all of their f’s and dot all of their j’s.Operator Overloading in C++2019-09-13T00:00:00-05:002019-09-13T00:00:00-05:00https://stevenbitner.github.io/posts/cpp-overloading-operators<p>What follows is an example of an overloaded operator for a class named <code class="language-plaintext highlighter-rouge">Foo</code>.</p>
<h2 id="motivation">Motivation</h2>
<p>Operators such as <code class="language-plaintext highlighter-rouge">+</code> are self explanatory, how would we add two Stocks together in a portfolio without it.
Why bother overloading the output operator, can’t we just use <code class="language-plaintext highlighter-rouge">ToString()</code>?</p>
<h3 id="syntactic-sugar">Syntactic sugar</h3>
<p>Which block of code below is easier to read:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="n">students</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">ToString</span><span class="p">()</span>
<span class="o"><<</span> <span class="s">" is in "</span> <span class="o"><<</span> <span class="n">classes</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">ToString</span><span class="p">()</span>
<span class="o"><<</span> <span class="s">" taught by "</span> <span class="o"><<</span> <span class="n">instructors</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">ToString</span><span class="p">();</span>
</code></pre></div></div>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="n">students</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="o"><<</span> <span class="s">" is in "</span> <span class="o"><<</span> <span class="n">classes</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="o"><<</span> <span class="s">" taught by "</span> <span class="o"><<</span> <span class="n">instructors</span><span class="p">[</span><span class="n">i</span><span class="p">];</span>
</code></pre></div></div>
<p>It’s a small thing, and not much of a change (syntactic sugar rarely is) but code will be written once and read many times.
Making the reading of the code easier on the eyes can make a large difference in time.</p>
<h3 id="data-types">Data types</h3>
<p>A <code class="language-plaintext highlighter-rouge">ToString()</code> method will require us to cast some class or instance data into strings.
This might not be a big deal, calling <code class="language-plaintext highlighter-rouge">to_string</code> on an integer is easy enough, but in the context of templates we can have some problems.
Try calling <code class="language-plaintext highlighter-rouge">to_string</code> on a string and watch your program crash.
Using streams is how we can make our implementation more flexible, and that’s never a bad thing.</p>
<h3 id="its-standard">It’s standard</h3>
<p>Did we call the method <code class="language-plaintext highlighter-rouge">ToString</code>, or <code class="language-plaintext highlighter-rouge">GetString</code>, or <code class="language-plaintext highlighter-rouge">toString</code> or <code class="language-plaintext highlighter-rouge">PrintObject</code>…you get the point.
Each class that gets built might have a different variation on what is created.
Sure, you can find the API in the header file and know the name, but why bother having to look it up each time you want to display an object.
You can also try to fix this through coding standards, but enforcement can become burdensome and a standard for outputting things already exists in C++, it is <code class="language-plaintext highlighter-rouge"><<</code>.</p>
<h2 id="sample-from-a-header-hpp-file">Sample from a header (.hpp) file</h2>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include <iostream>
</span>
<span class="k">class</span> <span class="nc">Foo</span>
<span class="p">{</span>
<span class="k">friend</span> <span class="n">std</span><span class="o">::</span><span class="n">ostream</span><span class="o">&</span> <span class="k">operator</span><span class="o"><<</span> <span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">ostream</span><span class="o">&</span> <span class="n">out</span><span class="p">,</span> <span class="k">const</span> <span class="n">Foo</span><span class="o">&</span> <span class="n">objectToDisplay</span><span class="p">);</span>
<span class="nl">private:</span>
<span class="kt">int</span> <span class="n">value</span> <span class="o">=</span> <span class="mi">77</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div></div>
<h2 id="sample-from-an-implementation-cpp-file">Sample from an implementation (.cpp) file</h2>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">std</span><span class="o">::</span><span class="n">ostream</span><span class="o">&</span> <span class="k">operator</span><span class="o"><<</span> <span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">ostream</span><span class="o">&</span> <span class="n">out</span><span class="p">,</span> <span class="k">const</span> <span class="n">Foo</span><span class="o">&</span> <span class="n">objectToDisplay</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">out</span> <span class="o"><<</span> <span class="s">"This Foo is great. It's value is "</span> <span class="o"><<</span> <span class="n">objectToDisplay</span><span class="p">.</span><span class="n">value</span><span class="p">;</span>
<span class="k">return</span> <span class="n">out</span><span class="p">;</span> <span class="c1">// must return the stream object to enable chaining</span>
<span class="p">}</span>
</code></pre></div></div>
<h2 id="lhs-and-rhs">LHS and RHS</h2>
<p>A function such as <code class="language-plaintext highlighter-rouge">myFoo.toString()</code> has a clear context and function name since it is all <strong>explicit</strong>.
In the case of an operator, in math or in C++, there is no context, simply a left-hand side and right-hand side operand.
Thus, the <code class="language-plaintext highlighter-rouge">operator<<</code> function name is <em>implied</em> by the call.
The arguments to the function are the left-hand side and right-hand side, respectively.
In the case of the output stream operator (<code class="language-plaintext highlighter-rouge"><<</code>), the left-hand side is the desired output stream, while the right-hand side is the object to be output.</p>
<h2 id="chaining">Chaining</h2>
<p>The return type of <code class="language-plaintext highlighter-rouge">std::ostream&</code> is no accident.
Essentially, we make the call with the stream on the left and the object on the right.
Those two statements are then combined with the return becoming the left hand side of the next call.</p>
<p>In math, we add integers in the following way: <code class="language-plaintext highlighter-rouge">1+2+3+4 = 3+3+4 = 6+4 = 10</code>.
At each step, we add the two leftmost integers and the result is an integer which is now the leftmost call to the next operation.
The same principle applies to any overloaded operator in C++.</p>
<h2 id="the-friend-zone">The “Friend Zone”</h2>
<p>We’re computer scientists and software developers, we’ve all been in the friend zone, but what does that mean in C++?
Notice in the sample implementation for <code class="language-plaintext highlighter-rouge">operator<<</code> <a href="#sample-from-an-implementation-cpp-file">above</a> we access the data member <code class="language-plaintext highlighter-rouge">value</code> of the <code class="language-plaintext highlighter-rouge">Foo</code> instance.
If we’ve encapsulated our data properly, then those data members are private, thus not accessible outside of our <code class="language-plaintext highlighter-rouge">Foo</code> class.
But this operator is one that we <em>trust</em> so we’re going to allow it to access those members anyway.
Just like in real life, we share our private information with our friends.
You can argue the merits of this approach versus its violation of pure encapsulation, but that is another discussion that is primarily a battle of louder opinions.</p>
<p>Why do we need it though, I mean this function would (presumably) be in the implementation file for <code class="language-plaintext highlighter-rouge">Foo</code>.
Because of how <code class="language-plaintext highlighter-rouge"><<</code> is called, it isn’t called within the <strong>context</strong> of a class instance.
Thus, when we define it, it is not resolved to the scope of the class.
Above, see that the function declaration isn’t given like this:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">friend</span> <span class="n">std</span><span class="o">::</span><span class="n">ostream</span><span class="o">&</span> <span class="n">Foo</span><span class="o">::</span><span class="k">operator</span><span class="o"><<</span> <span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">ostream</span><span class="o">&</span> <span class="n">out</span><span class="p">,</span> <span class="k">const</span> <span class="n">Foo</span><span class="o">&</span> <span class="n">objectToDisplay</span><span class="p">)</span>
</code></pre></div></div>
<p>It’s given without the <code class="language-plaintext highlighter-rouge">Foo::</code> scope resolution, like this:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">friend</span> <span class="n">std</span><span class="o">::</span><span class="n">ostream</span><span class="o">&</span> <span class="k">operator</span><span class="o"><<</span> <span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">ostream</span><span class="o">&</span> <span class="n">out</span><span class="p">,</span> <span class="k">const</span> <span class="n">Foo</span><span class="o">&</span> <span class="n">objectToDisplay</span><span class="p">)</span>
</code></pre></div></div>
<p>That’s because we don’t say:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Foo</span> <span class="n">myFoo</span><span class="p">;</span>
<span class="n">myFoo</span><span class="p">.</span><span class="o"><<</span><span class="p">;</span>
</code></pre></div></div>
<p>but rather</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Foo</span> <span class="n">myFoo</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="n">myFoo</span><span class="p">;</span>
</code></pre></div></div>
<h2 id="questions">Questions?</h2>
<p>I hope this helps clear some things up.
If you have questions, ask Google or <a href="https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading">Stackoverflow</a>.
If you are my student, come on by my office hours and we’ll get it figured out together.</p>Steve BitnerWhat follows is an example of an overloaded operator for a class named Foo.