 
    
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>c language Archives - Complete, Concrete, Concise</title>
	<atom:link href="https://complete-concrete-concise.com/tag/c-language/feed/" rel="self" type="application/rss+xml" />
	<link>https://complete-concrete-concise.com/tag/c-language/</link>
	<description>Practical Information Without The Bloat</description>
	<lastBuildDate>Thu, 09 Jun 2011 08:04:32 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>
	<item>
		<title>C as a Strongly Typed Language</title>
		<link>https://complete-concrete-concise.com/programming/c/c-as-a-strongly-typed-language/</link>
		
		<dc:creator><![CDATA[richardsplanet]]></dc:creator>
		<pubDate>Thu, 09 Jun 2011 08:04:32 +0000</pubDate>
				<category><![CDATA[C]]></category>
		<category><![CDATA[c language]]></category>
		<category><![CDATA[c programming]]></category>
		<category><![CDATA[creating new types]]></category>
		<category><![CDATA[strong types]]></category>
		<category><![CDATA[strongly typed]]></category>
		<category><![CDATA[weak types]]></category>
		<category><![CDATA[weakly typed]]></category>
		<guid isPermaLink="false">http://complete-concrete-concise.com/programming/c/c-as-a-strongly-typed-language</guid>

					<description><![CDATA[<p>Contrary to popular belief, C is a strongly typed language; the problem is that C programming practice favours using weak typing. What is a Type? A type is something that has a set of values associated with it, a set of operations that can be performed on it, and a representation (how it looks at [&#8230;]</p>
<p>The post <a href="https://complete-concrete-concise.com/programming/c/c-as-a-strongly-typed-language/">C as a Strongly Typed Language</a> appeared first on <a href="https://complete-concrete-concise.com">Complete, Concrete, Concise</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div class="c1">
<p>Contrary to popular belief, C is a strongly typed language; the problem is that C programming practice favours using weak typing.</p>
</div>
<h1>What is a Type?</h1>
<p>A type is something that has </p>
<ol>
<li>a set of values associated with it, </li>
<li>a set of operations that can be performed on it, </li>
<li>and a representation (how it looks at the machine level). </li>
</ol>
<p>This sounds similar to objects from Object Oriented Programming (OOP) but objects have 3 additional properties over types:</p>
<ol>
<li>inheritance &#8211; child objects inherit the operations of the parent object</li>
<li>extensibility &#8211; child objects can extend the parent object</li>
<li>polymorphism &#8211; operations on an object don&#8217;t have to be bound at compile time, they can be determined at runtime.</li>
</ol>
<h1>Example of a Type</h1>
<p>There are 3 commonly used temperature scales: Celsius, Fahrenheit and Kelvin.</p>
<p>Each has a definite minimum value, an unspecified maximum value and you can perform various operations on them (addition, subtraction, scaling, conversion, averaging, etc).</p>
<p>There is no problem in adding two &deg;C values together, or two &deg;F values together.</p>
<p> I am sure you would agree that it is an error to add a &deg;C value to a &deg;F value &#8211; since they are not the same type and the result is meaningless.</p>
<p>It would also be incorrect to assign a &deg;F value to a &deg;C variable. The proper way to assign a value of one type to another is by a conversion.</p>
<h1>The Common Way These Types Would be Coded in C</h1>
<p>The typical C programmer, when coding types for &deg;C and &deg;F would first determine what is the range of values required and what precision is required.</p>
<p>If we don&#8217;t care about fractions of a degree, then some sort of integer representation is fine. If fractions of a degree are important then we would consider using either a fixed point representation or a floating point representation. </p>
<p>Good programming practice dictates that we don&#8217;t use naked fundamental C types and instead use <code>typedef</code> to define the type because </p>
<ol>
<li>this makes the code more self documenting and </li>
<li>if we need to change the representation at a later time, we only have to change it in one place instead of hunting through the code:</li>
</ol>
<div class="c2"><code>typedef float temperature_C;<br />
typedef float temperature_F;</code></div>
<h1>The Problem with the Normal Way of Defining a Type</h1>
<p>Unfortunately, we haven&#8217;t defined any new types. We have only defined new names for an existing fundamental C type.</p>
<p>The code we write looks like it is using custom types:</p>
<div class="c2"><code>/* declare variables */<br />
temperature_C c;<br />
temperature_F f;</code></div>
<p>Unfortunately, we can still mix types:</p>
<div class="c2"><code>c = c + f;</code></div>
<p>and the compiler will not complain because it knows that <code>c</code> and <code>f</code> are both of type <code>float</code>. The compiler is unable to enforce the meaning of the types &#8211; that responsibility falls on the programmer who has to ensure the operation makes sense. </p>
<p>Imagine you are developing software for a baby bath monitor. One of the things the monitor does is check if the bath water is too hot (we don&#8217;t want to scald the baby). As a programmer you write a suitable function:</p>
<p><code></p>
<pre>_Bool is_bath_too_hot (temperature_F t)
{
    if (t > MAX_SAFE_TEMPERATURE)
    {
        return true;
    }
    return false;
}</pre>
<p></code></p>
<p>The problem with this function is that while it looks like it takes a parameter of <code>temperature_F</code>, in reality, it will accept any floating point number including a <code>temperature_C</code>. A MAX_SAFE_TEMPERATURE for bath water is 100&deg;F (or 38&deg;C). By accidentally passing a <code>temperature_C</code> to the function, you risk approving water that is dangerously hot (100&deg;C is the boiling point of water).</p>
<p>Most programmers would say that is just the nature of the language, there are a limited number of fundamental types and it is the programmer&#8217;s responsibility to use those types responsibly.</p>
<h1>Creating Your Own Types in C</h1>
<p>We are not limited to the fundamental data types in C, we can create our own data types.</p>
<p>Every <code>struct</code> and every <code>union</code> in C is a new data type. Even if the representation is the same, you cannot assign one <code>struct</code> to different <code>struct</code></p>
<p><code></p>
<pre>struct temperature_C
{
    float value;
};
struct temperature_F
{
    float value;
};
.
.
.
struct temperature_C c;
struct temperature_F f;
c = f; /* this will not compile because they are different types */</pre>
<p></code></p>
<p>Of course, it is ugly to have to preface every use of the type with <code>struct</code>, so you are more likely to <code>typedef</code> it:</p>
<p><code></p>
<pre>typedef struct
{
    float value;
} temperature_C;
typedef struct
{
    float value;
} temperature_F;</pre>
<p></code><br />
Now you can use them as though they were plain types:</p>
<div class="c2"><code>temperature_C c;<br />
temperature_F f;<br />
c = f; /* this will not compile because they are different types */</code></div>
<h1>Why You are Not Likely to Code This Way</h1>
<p>All we have is a new type, but we have no operations on it (aside from assignment).</p>
<p>This means we have to define all the operations we want for this type. Since C does not allow operator overloading, this means we lose the convenience of doing:</p>
<div class="c2"><code>a = b + c;</code></div>
<p>and, instead, have to write:</p>
<div class="c2"><code>a = add(b, c);</code></div>
<p>Worse yet, C does not allow function overloading either, so all function names must be unique. To make each function name unique, we will probably resort to decorating each function name with the type name.</p>
<div class="c2"><code>a = add_my_type(b, c);</code></div>
<p>None of the library functions will work with it. You can&#8217;t use <code>log</code> or <code>sin</code> or <code>printf</code> with these types &#8211; unless you write your own wrappers.</p>
<div class="c1">
<p><strong>If type safety is important, this is the only way to go &#8211; aside from changing languages.</strong></p>
</div>
<h1>Performance Costs</h1>
<p>Aside from wrapping up a fundamental type in a <code>struct</code> and creating all those new functions what is the performance overhead?</p>
<p>There is <strong><u>none </u></strong>&#8211; if you use inline functions (available in C99 and later). </p>
<p>The new type doesn&#8217;t take up any more space than the fundamental type it wraps up. The compiler doesn&#8217;t create extra code for it.</p>
<p>Writing </p>
<p><code></p>
<pre>inline my_type <strong>add_my_type</strong> (my_type a, my_type b)
{
    my_type t;
    t.value = a.value + b.value;
    return t;
}</pre>
<p></code></p>
<p>gets compiled as a simple addition. There is no function call overhead, no extra instructions inserted by the compiler.</p>
<p>Using GCC version 4.4.1, there was no difference for the assembly output for these two declarations and operations:</p>
<div class="c2"><code>temperature_C c, d;<br />
c = add_temperature_C(c, d);<br />
float a, b;<br />
a = a + b;</code></div>
<h1>Macros Make Life Easier</h1>
<p>It is a lot of typing to create a new type and write fundamental operations for it. Fortunately, macros can save us a lot of work.</p>
<p>The macro <code>new_type</code> takes two parameters: <code>name</code> which is the name of the new type and <code>type</code> which is the representation (int, short, char, float, etc) for the type.</p>
<p>It creates</p>
<ul>
<li>the new type with the name specified</li>
<li>an initializer</li>
<li>add function</li>
<li>subtract function</li>
<li>multiply function</li>
<li>divide function</li>
<li>greater than comparison function</li>
<li>greater than or equal to comparison function</li>
<li>less than comparison function</li>
<li>less than or equal to comparison function</li>
<li>equality test function</li>
<li>non-equality test function</li>
<li>value function that returns the basic C type</li>
</ul>
<p><code></p>
<pre>#define new_type(name, type) \
typedef struct \
{ \
    type value; \
} name; \
inline name name##_(type v) \
{ \
    name t; \
    t.value = v; \
    return t; \
} \
inline name add_##name(name a, name b) \
{ \
    name t; \
    t.value = a.value + b.value; \
    return t; \
} \
inline name sub_##name(name a, name b) \
{ \
    name t; \
    t.value = a.value - b.value; \
    return t; \
} \
inline name mul_##name(name a, name b) \
{ \
    name t; \
    t.value = a.value * b.value; \
    return t; \
} \
inline name div_##name(name a, name b) \
{ \
    name t; \
    t.value = a.value / b.value; \
    return t; \
} \
inline _Bool gt_##name(name a, name b) \
{ \
    return a.value > b.value; \
} \
inline _Bool gte_##name(name a, name b) \
{ \
    return a.value >= b.value; \
} \
inline _Bool lt_##name(name a, name b) \
{ \
    return a.value < b.value; \
} \
inline _Bool lte_##name(name a, name b) \
{ \
    return a.value <= b.value; \
} \
inline _Bool eq_##name(name a, name b) \
{ \
    return a.value == b.value; \
} \
inline _Bool neq_##name(name a, name b) \
{ \
    return a.value != b.value; \
} \
inline type value_##name(name a) \
{ \
    return a.value; \
} \</pre>
<p></code></p>
<p>Creating a <code>temperature_C</code> type is simply:</p>
<div class="c2"><code>new_type(temperature_C, float);</code></div>
<p>Which gives you:</p>
<div class="c2"><code>temperature_C</code></p>
<p>The new type.</p>
<p><code>temperature_C <strong>temperature_C_</strong> (float v)</code></p>
<p>An initializing / casting function</p>
<p><code>temperature_C <strong>add_temperature_C</strong> (temperature_C a, temperature_C b)</code></p>
<p>Returns a + b.</p>
<p><code>temperature_C <strong>sub_temperature_C</strong> (temperature_C a, temperature_C b)</code></p>
<p>Returns a - b.</p>
<p><code>temperature_C <strong>mul_temperature_C</strong> (temperature_C a, temperature_C b)</code></p>
<p>Returns a * b.</p>
<p><code>temperature_C <strong>div_temperature_C</strong> (temperature_C a, temperature_C b)</code></p>
<p>Returns a / b.</p>
<p><code>_Bool <strong>gt_temperature_C</strong> (temperature_C a, temperature_C b)</code></p>
<p>Returns a > b.</p>
<p><code>_Bool <strong>gte_temperature_C</strong> (temperature_C a, temperature_C b)</code></p>
<p>Returns a >= b.</p>
<p><code>_Bool <strong>lt_temperature_C</strong> (temperature_C a, temperature_C b)</code></p>
<p>Returns a < b.</p>
<p><code>_Bool <strong>lte_temperature_C</strong> (temperature_C a, temperature_C b)</code></p>
<p>Returns a <= b.</p>
<p><code>_Bool <strong>eq_temperature_C</strong> (temperature_C a, temperature_C b)</code></p>
<p>Returns a == b.</p>
<p><code>_Bool <strong>neq_temperature_C</strong> (temperature_C a, temperature_C b)</code></p>
<p>Returns a != b.</p>
<p><code>float <strong>value_temperature_C</strong> (temperature_C a)</code></p>
<p>Returns the raw value of the type. This makes it easier to use the type with existing library functions like <code>printf</code> or in a <code>switch</code> statement.</p>
</div>

<p>The post <a href="https://complete-concrete-concise.com/programming/c/c-as-a-strongly-typed-language/">C as a Strongly Typed Language</a> appeared first on <a href="https://complete-concrete-concise.com">Complete, Concrete, Concise</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
