{"id":5121,"date":"2020-12-10T12:02:39","date_gmt":"2020-12-10T17:02:39","guid":{"rendered":"https:\/\/www.caskeys.com\/dc\/?p=5121"},"modified":"2025-05-21T00:17:11","modified_gmt":"2025-05-21T04:17:11","slug":"preprocessing-constants","status":"publish","type":"post","link":"https:\/\/www.caskeys.com\/dc\/preprocessing-constants\/","title":{"rendered":"Tutorial &#8211; Constants"},"content":{"rendered":"\n<p>This tutorial covers one of the most basic concepts of programming\/scripting: User defined constants. It is meant for beginning coders and <a href=\"http:\/\/www.chronocrash.com\" target=\"_blank\" rel=\"noopener noreferrer\">OpenBOR<\/a> script writers. Upon completion, you should understand all of the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The definition of <em>&#8220;Constant&#8221;<\/em> in computer science (programming) as opposed to other uses of the term (such as mathematics).<\/li>\n\n\n\n<li>How constants work in relation to other types of identifiers.<\/li>\n\n\n\n<li>Where and how to apply constants.<\/li>\n\n\n\n<li>Use of constants within the&nbsp;<a href=\"http:\/\/www.chronocrash.com\" target=\"_blank\" rel=\"noopener noreferrer\">OpenBOR<\/a> scripting engine.<\/li>\n<\/ul>\n\n\n\n<h1 class=\"wp-block-heading\">Constants vs. Literals &amp; Variables<\/h1>\n\n\n\n<p>To fully comprehend why constants are useful it is imperative to understand what a constant really <em>is<\/em>, especially compared to variables and literals. Literals are of particular note because it is very easy to confuse literals with constants. In the field of computer science, variables, constants and literals are <em>usually<\/em> defined as follows (Rao, 2017):<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Variable: <\/strong>A variable is a storage location and an associated identifier which contains some known or unknown quantity or information, a value.<\/li>\n\n\n\n<li><strong>Constant: <\/strong>A constant is an identifier with an associated value that the program can not normally modify.<\/li>\n\n\n\n<li><strong>Literal: <\/strong>A literal is a notation for representing a fixed value.<\/li>\n<\/ul>\n\n\n\n<p>Note the unfortunate caveat: <em>&#8220;usually&#8221;<\/em>. This is because some languages (C in particular) refer to both literals and constants as <em>&#8220;constants&#8221;<\/em> (<em>Constants<\/em>, 2020). They are then differentiated as <em>&#8220;literal constants&#8221;<\/em> and <em>&#8220;symbolic constants&#8221;<\/em> respectively. In programing circles, numeric literals are also called <em>&#8220;magic numbers&#8221;<\/em> (<em>Definition of constants and magic numbers<\/em> 2001). To avoid confusion between them we will henceforth only use the references <em>&#8220;literal&#8221;<\/em> and <em>&#8220;constant&#8221;.<\/em><\/p>\n\n\n\n<p>In practical terms, you may think of variables as named values that you can modify, constants as named values that you can&#8217;t modify and literals as values that mean exactly what they say. The question is how do these definitions and meanings apply in real world programming. To find out let&#8217;s start with variables and literals using this example multiplier:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">i*2 = y<\/pre>\n\n\n\n<p>Applying our definitions above, there are&nbsp;two variables (<b>i<\/b>, <b>y<\/b>) and a single literal (<b>2<\/b>) in play:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><b>i<\/b> represents some number that can be whatever we want.<\/li>\n\n\n\n<li><b>y<\/b> is the product result.<\/li>\n\n\n\n<li><b>2<\/b> is just two &#8211; it&#8217;s a literal value.<\/li>\n<\/ul>\n\n\n\n<p>Now observe as we translate our equation into some code and see it in action:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: Code:; notranslate\" title=\"Code:\">\nint i = 0;\nint y = 1;\n\nfor (i = 0; i &lt; 10; i++)\n{   \n    y = y * 2;\n    print(&quot;Result %i: %i\\n&quot;, i+1, y);\n}\n<\/pre><\/div>\n\n\n<p>This will get us a simple geometric progression. First, we assign variable <code>i<\/code> a value of zero. Then we increment <code>i<\/code> by one in a loop until it is no longer less than ten. At each pass we assign <code>y<\/code> the product of <code>y * 2<\/code>. Then we print the cursor row and current value of <code>y<\/code>, giving us the following output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Result 1: 2<br>Result 2: 4<br>Result 3: 8<br>Result 4: 16<br>Result 5: 32<br>Result 6: 64<br>Result 7: 128<br>Result 8: 256<br>Result 9: 512<br>Result 10: 1024<\/pre>\n\n\n\n<p>Observe how our literal value <code>2<\/code> worked in relation to the variables surrounding it. Note the number <code>10<\/code> is also a literal, but for simplicity let&#8217;s just worry about <code>2<\/code>. We could run this loop to infinity and it will always multiply <code>y * 2<\/code> and assign the result to <code>y<\/code>. The variables i and y are continuously modified while <code>2<\/code> never changes. Easy enough yes? Remember:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>Literals are static values written directly into source code; they &#8220;literally&#8221; mean what they say. Variables are IDs which are assigned values that can be (and usually are) modified while the program executes.<\/p>\n<\/blockquote>\n\n\n\n<p>Now what would happen if we need to calculate our equation again, only dividing by <code>2<\/code> rather than multiplying? As an example, we&#8217;ll make a copy of our loop with a minor modification and run both in sequence.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; highlight: [8,16]; title: Code:; notranslate\" title=\"Code:\">\nint i = 0;\nint y = 1;\n\nprint(&quot;\\n Multiply %i:\\n\\n&quot;, 2);\n\nfor (i = 0; i &lt; 10; i++)\n{   \n    y = y * 2;\n    print(&quot;Result %i: %i\\n&quot;, i+1, y);\n}\n\nprint(&quot;\\n\\n Divide %i:\\n\\n&quot;, 2);\n\nfor (i = 0; i &lt; 10; i++)\n{   \n    y = y \/ 2;\n    print(&quot;Result %i: %i\\n&quot;, i+1, y);\n}\n\n<\/pre><\/div>\n\n\n<p>We&#8217;ll get the following output.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Multiply 2:<br><br>Result 1: 2<br>Result 2: 4<br>Result 3: 8<br>Result 4: 16<br>Result 5: 32<br>Result 6: 64<br>Result 7: 128<br>Result 8: 256<br>Result 9: 512<br>Result 10: 1024<br><br>Divide: 2<br><br>Result 1: 512<br>Result 2: 256<br>Result 3: 128<br>Result 4: 64<br>Result 5: 32<br>Result 6: 16<br>Result 7: 8<br>Result 8: 4<br>Result 9: 2<br>Result 10: 1<br><\/pre>\n\n\n\n<p>As you can see in the second example, we start with the geometric progression pattern from earlier and then reverse it. For purposes of our example, the output is not that important. What matters here is how we use the literal 2 four times in succession &#8211; once for each label and each operation. No problem thus far. But suppose later we need to substitute <code>2<\/code> with <code>10<\/code>? Just edit the code and be done right? With examples like this, of course! Unfortunately real world coding is not so simple. Consider a real script or program. Even a something simple like some of the scripts powering this website may comprise several pages of code. For perspective, the <a href=\"https:\/\/github.com\/DCurrent\/openbor\" data-type=\"URL\" data-id=\"https:\/\/github.com\/DCurrent\/openbor\">OpenBOR engine<\/a> contains ~600K lines of source code. Some of the largest applications can number in the millions. Now imagine trying to locate and edit every instance of <code>2<\/code>. Or worse, trying to locate specific instances of <code>2<\/code>, and leaving the rest alone. Even with advanced regex expressions, assuming those are available at all, copy\/paste operations can be effectively impossible. Hand editing is time prohibitive and error prone. This is where constants are so valuable. Let&#8217;s look at our example once again, with a little something extra added.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; highlight: [1,6,10,14,18]; title: Code:; notranslate\" title=\"Code:\">\n#define SOMENUM 2\n\nint i = 0;\nint y = 1;\n\nprint(&quot;\\n Multiply %i:\\n\\n&quot;, SOMENUM);\n\nfor (i = 0; i &lt; 10; i++)\n{   \n    y = y * SOMENUM;\n    print(&quot;Result %i: %i\\n&quot;, i+1, y);\n}\n\nprint(&quot;\\n\\n Divide %i:\\n\\n&quot;, SOMENUM);\n\nfor (i = 0; i &lt; 10; i++)\n{   \n    y = y \/ SOMENUM;\n    print(&quot;Result %i: %i\\n&quot;, i+1, y);\n}\n<\/pre><\/div>\n\n\n<p>As you&#8217;ve no doubt guessed, this and the previous example produce identical results. The difference is we no longer rely on a literal <code>2<\/code>. Instead, this line creates a constant identified as <code>SOMENUM<\/code> and assigns it the value of <code>2<\/code>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: Code:; notranslate\" title=\"Code:\">\n#define SOMENUM 2\n<\/pre><\/div>\n\n\n<p>Just as <code>i<\/code> represents a loop counter value, <code><code>SOMENUM<\/code><\/code> represents the number <code>2<\/code>. But unlike <code>i<\/code> and <code>Y<\/code>, <code><code>SOMENUM<\/code><\/code> can never change while the program is running. It maintains a <em>constant<\/em> value, hence the name. Effectively we have given a potentially VERY common value (<strong>2<\/strong>) its own unique identification. Attaching an identification to values that never change is an extra step that may seem silly at first, but in the long run actually saves you time. It is almost universally considered best practice (<em>Recommended C Style and Coding Standards<\/em> 2000).<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>There is no need to modify the code in multiple places. If we want to substitute our constant value for something else, we merely change the <em>#define<\/em>. Depending on scope of the program, this can range from being a simple time saver to enabling adjustments that are otherwise untenable or virtually impossible.<\/li>\n\n\n\n<li>You may give constants nearly any imaginable label. That in turn enables creation of organized naming conventions for cleaner, more human readable code. This means superior design malleability, greater run time stability, and easier debugging when anomalies do occur.<\/li>\n\n\n\n<li>It is possible to write programs with configuration blocks for simplistic modification of basic behavior and quick porting to other hardware platforms.<\/li>\n\n\n\n<li>Separation of code and content! Why write a formula that only adds 2+2 when X+Y can perform the same task with infinite re-usability?<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">How To Use Constants In Your Code<\/h2>\n\n\n\n<p>Using constants is amazingly simple, but like any programming technique also sometimes mercurial. Every coding environment will have its own set of operators, methods, capabilities, and quirks. I will be focusing mainly on the the C based scripting engine of <a href=\"http:\/\/www.chronocrash.com\" target=\"_blank\" rel=\"noopener noreferrer\">OpenBOR<\/a>. A cursory Google search should provide all the instruction you need for other tools of choice.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><a href=\"http:\/\/www.chronocrash.com\" target=\"_blank\" rel=\"noopener noreferrer\">OpenBOR<\/a><\/h3>\n\n\n\n<p><a href=\"http:\/\/www.chronocrash.com\" target=\"_blank\" rel=\"noopener noreferrer\">OpenBOR&#8217;s<\/a> scripting engine is a C derivative and supports the define directive for constants. A define comprises three parts:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Definition: Always <em>&#8220;#define&#8221;.<\/em><\/li>\n\n\n\n<li>Identification: This is the name of your constant.<\/li>\n\n\n\n<li>Token: The value. This is what the computer will interpret whenever the constant is encountered in code.<\/li>\n<\/ol>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: Code:; notranslate\" title=\"Code:\">\n#define SOME_IDENTIFICATION somevalue\n<\/pre><\/div>\n\n\n<p>Don&#8217;t worry about memory or CPU resources. The define directive is  prepossessed, meaning the application handles it on start up. In other words, constants have no memory or run-time CPU cost. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">General Tips<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Naming Conventions<\/h4>\n\n\n\n<p>Decide on a naming convention before you start writing code. You will want names that are unique enough to avoid conflict while remaining reasonably succinct. Common practice is to use all caps for the identifier, with an underscore separator between each segment. The segments themselves should maintain Big Endian order.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: Code:; notranslate\" title=\"Code:\">\n#define BOVINAE_BISON\t\t\t\"Bison\"\t\/\/ Best in the west!\n#define BOVINAE_BOS\t\t\t\t\"Cow\"\t\/\/ It's what's for dinner.\n#define SIZE_LARGE\t\t\t\t16\t\t\/\/ Full meal.\n#define SIZE_MEDIUM\t\t\t\t12\t\t\/\/ Light snack.\n#define SIZE_SMALL\t\t\t\t10\t\t\/\/ For the kiddies.\n#define TEMP_DONE_MAX\t\t\t100\t\t\/\/ Mmmmummm, that's the stuff!\n#define TEMP_DONE_MIN\t\t\t71\t\t\/\/ Nice and brown.\n#define TEMP_MEDIUM_MAX\t\t\t65\t\t\/\/ Little cold, but not bad.\n#define TEMP_MEDIUM_MIN\t\t\t60\t\t\/\/ In a hurry?\n#define TEMP_MEDIUM_WELL_MAX\t69\t\t\/\/ Not too shabby.\n#define TEMP_MEDIUM_WELL_MIN\t65\t\t\/\/ Add some Worcestershire and we'll talk.\n#define TEMP_RARE_MAX\t\t\t55\t\t\/\/ Somebody call a blood bank.\n#define TEMP_RARE_MIN\t\t\t52\t\t\/\/ Moo!\n<\/pre><\/div>\n\n\n<p>Note the larger group of Subfamily appears first, followed by Genus. We follow a similar convention for cut size and cooking temperature. Who&#8217;s in the mood for a SIZE_LARGE BOVINAE_BOS TEMP_WELL_MAX?<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Text File Use<\/h4>\n\n\n\n<p>In <a href=\"http:\/\/www.chronocrash.com\" target=\"_blank\" rel=\"noopener noreferrer\">OpenBOR<\/a>, any constants available in a model&#8217;s animation script are also available in the model text. This means constants are usable inside of <em>@script<\/em> tags or as function arguments in <em>@cmd<\/em> tags.<\/p>\n\n\n\n<p>Reading this function call is very difficult unless the creator has a perfect memory, and it&#8217;s impossible for anyone else&#8230;.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: Code:; notranslate\" title=\"Code:\">\n@cmd set_bind_state 7 1\n<\/pre><\/div>\n\n\n<p>&#8230;but with constants, the creator can instantly identify what the function call should do, and if need be can easily find related calls with a text search. Other readers may not understand right away, but they can probably get a rough idea and debug from context:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: Code:; notranslate\" title=\"Code:\">\n@cmd set_bind_state BIND_STATE_FACE_DOWN DIRECTION_RIGHT\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">When\/Where Should Constants Be Used?<\/h2>\n\n\n\n<p>One of the more common questions involving constants is <em>&#8220;When should I use them?&#8221;<\/em> The answer is <em>&#8220;whenever possible.&#8221;<\/em> As a more usable interpretation of <em>&#8220;whenever possible&#8221;<\/em>, consider the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Is the value static?<\/li>\n\n\n\n<li>Will you use the value more than once?<\/li>\n\n\n\n<li>Does the value lack infinite range and variation?<\/li>\n<\/ul>\n\n\n\n<p>If the value fits these criteria, then replace it with a constant. Remember, defined constants in OpenBOR are &#8220;free&#8221;, they don&#8217;t consume any more resources than the literal values they replace. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Final Words<\/h2>\n\n\n\n<p>I hope this helps you to understand how simple, elegant and useful constants can be, and I would encourage you to make full use of them in your own projects. Lastly, please feel free to leave comments below with any questions or opinions you may have, and I will see to them in short order. If you have any questions about the OpenBOR engine, stop by at <a href=\"http:\/\/www.chronocrash.com\" data-type=\"URL\" data-id=\"www.chronocrash.com\">ChronoCrash<\/a> and we&#8217;ll be glad to help.<\/p>\n\n\n\n<p>Thanks for reading!<br><a rel=\"noopener noreferrer\" href=\"https:\/\/www.caskeys.com\/dc\/?page_id=2\" target=\"_blank\">DC<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<p><em>C Constants<\/em>. (2020). <a href=\"https:\/\/www.w3schools.in\/c-tutorial\/constants\/\">https:\/\/www.w3schools.in\/c-tutorial\/constants\/<\/a>.<\/p>\n\n\n\n<p>Def. (2001). Definition of constants and magic numbers. <a href=\"https:\/\/www.inf.unibz.it\/~calvanese\/teaching\/05-06-ip\/lecture-notes\/uni04\/node17.html\">https:\/\/www.inf.unibz.it\/~calvanese\/teaching\/05-06-ip\/lecture-notes\/uni04\/node17.html<\/a>.<\/p>\n\n\n\n<p>Rao, S. (2017, January 27). <em>Informit<\/em>. InformIT. <a href=\"https:\/\/www.informit.com\/articles\/article.aspx?p=2755729\">https:\/\/www.informit.com\/articles\/article.aspx?p=2755729<\/a>.<\/p>\n\n\n\n<p>Def. (2001). Definition of constants and magic numbers. <a href=\"https:\/\/www.inf.unibz.it\/~calvanese\/teaching\/05-06-ip\/lecture-notes\/uni04\/node17.html\">https:\/\/www.inf.unibz.it\/~calvanese\/teaching\/05-06-ip\/lecture-notes\/uni04\/node17.html<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<p>Originally published <a href=\"https:\/\/www.caskeys.com\/dc\/preprocessing-constants-in-progress\/\">2013-02-04<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A tutorial on the use of constants with and outside of OpenBOR scripting.<\/p>\n","protected":false},"author":1,"featured_media":6215,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[71],"tags":[213,232,289,298],"class_list":["post-5121","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology-temerity","tag-coding-constants","tag-applications-openbor","tag-coding-openbor-script","tag-technology-temerity"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/www.caskeys.com\/dc\/wp-content\/uploads\/2016\/11\/logo-openbor-3.png","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p5lNM5-1kB","jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/www.caskeys.com\/dc\/wp-json\/wp\/v2\/posts\/5121","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.caskeys.com\/dc\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.caskeys.com\/dc\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.caskeys.com\/dc\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.caskeys.com\/dc\/wp-json\/wp\/v2\/comments?post=5121"}],"version-history":[{"count":139,"href":"https:\/\/www.caskeys.com\/dc\/wp-json\/wp\/v2\/posts\/5121\/revisions"}],"predecessor-version":[{"id":7322,"href":"https:\/\/www.caskeys.com\/dc\/wp-json\/wp\/v2\/posts\/5121\/revisions\/7322"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.caskeys.com\/dc\/wp-json\/wp\/v2\/media\/6215"}],"wp:attachment":[{"href":"https:\/\/www.caskeys.com\/dc\/wp-json\/wp\/v2\/media?parent=5121"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.caskeys.com\/dc\/wp-json\/wp\/v2\/categories?post=5121"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.caskeys.com\/dc\/wp-json\/wp\/v2\/tags?post=5121"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}