<?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>engin aydogan &#187; c</title>
	<atom:link href="http://engin.bzzzt.biz/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://engin.bzzzt.biz</link>
	<description>&#039;s journal</description>
	<lastBuildDate>Thu, 02 Feb 2012 21:22:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Macros in C/C++, the right way.</title>
		<link>http://engin.bzzzt.biz/2009/12/12/macros-in-c-the-right-way/</link>
		<comments>http://engin.bzzzt.biz/2009/12/12/macros-in-c-the-right-way/#comments</comments>
		<pubDate>Sat, 12 Dec 2009 10:09:33 +0000</pubDate>
		<dc:creator>engin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[c]]></category>

		<guid isPermaLink="false">http://engin.bzzzt.biz/?p=50</guid>
		<description><![CDATA[When used appropriately macros are very useful, yet they are very easy to misuse. Before getting into cons and pros, first lets make sure if we really know what is a macro and how does it work.
Roughly there are three stages of compilation in C; preprocessing, compiling, linking. It really makes  [...]]]></description>
			<content:encoded><![CDATA[<p>When used appropriately macros are very useful, yet they are very easy to misuse. Before getting into cons and pros, first lets make sure if we really know what is a macro and how does it work.</p>
<p>Roughly there are three stages of compilation in C; preprocessing, compiling, linking. It really makes sense and it is very easy to understand, don&#8217;t think of this as a complex deal. We&#8217;ll mostly talk about the preprocessor stage in this post. As the name implies, this stage just pre-processes the source code before compiling it, it all happens prior to compiling and that&#8217;s it. Preprocessing includes defining some macros, and replacing each macro found in the source code with its value, so that it can be compiled. So get this right once and for all, macros are processed before compilation, they won&#8217;t be in the run-time code.</p>
<p>As an exercise you can use -E parameter of GCC, which will make it stop right after the preprocessing stage.</p>
<p>Now, let&#8217;s begin with a few examples;</p>
<pre>#define ERROR_SEEK 152
if( errno == ERROR_SEEK )
{
    // Handle the error.
}</pre>
<p>This directive defines a macro ERROR_SEEK. Preprocessor will replace every occurrences of ERROR_SEEK with 152 prior to compiling. So, the code that is going to be sent to compiler will have &#8220;if( errno == 152)&#8221; not the ERROR_SEEK because the compiler simply does not know what ERROR_SEEK is. Nothing fancy, dead simple. But it makes the code much more readable. Look at this example;</p>
<pre>#ifdef __GNUC__
#define COMPILER "gcc"
#else
#define COMPILER "proprietary"
#endif</pre>
<p>If __GNUC__ is defined somehow then every occurrences of COMPILER will be replaced with &#8220;gcc&#8221; and &#8220;proprietary&#8221; otherwise. Please note that this all happens before compilation, and this will not result in any executable code. In this special case __GNUC__ is defined by GCC itself. Though we can define a macro via #define directive in the source code, or with -D parameter of the compiler (which will work on most compilers).</p>
<p>Actually the name preprocessor says it all. All these preprocessor directives are pre processed before compilation. Makes sense uh ? Now I think we begin to understand the nature of macros/preprocessors.</p>
<p>Macros can be used to</p>
<ul>
<li>Improve readability (ERROR_SEEK is much more meaningful than 152)</li>
<li>Improve maintainability (When you change ERROR_SEEK in one header, it will be replaced all over the source code)</li>
<li>Ensuring that a block of code is inlined (more on this later)</li>
</ul>
<p>Though, if misused, the first two list items above will do  just the opposite :)</p>
<p>As for the possible disadvantages of preprocessors</p>
<ul>
<li>Could make debugging harder as lines of source lines before and after the preprocessing will be different, so debugger can be confused while stepping the executable code and matching which source line of code it is.</li>
<li>It is easy to misuse preprocessors.</li>
<li>Could cause trouble to static code analyzers.</li>
</ul>
<p>Now, possible misuse scenarios:</p>
<h2>1. Operator precedence</h2>
<p>The most common misuse scenario which you&#8217;ll see in almost every C book is this;</p>
<pre>#define FOO_CONST 83+22
printf("%d\n", FOO_CONST * 5 ); // This macro will expand to 83 + 22 *  5, hence will result 193.</pre>
<p>One could expect the result to be printed 525. But operator precedence would make the calculation 22 * 5 first, then add 83 to the result, so you&#8217;ll see 193 as a result instead of 525. Fixing this problem is easy;</p>
<pre>#define FOO_CONST (83+22)
printf("%d\n", FOO_CONST * 5 ); // This macro will expand to (83+22) * 5, hence will result 525.</pre>
<p>Enclosing the value of a macro is an easy way to ensure that they are evaluated in the right order.</p>
<h2>2. Multiple statements</h2>
<p>You can use multiple-statement macros to force inlining of a code block. Though note that this will increase the code size of your program. Anyway, the problem with the multiple-statements is a less known problem. Now, look at this.</p>
<pre>#define HELLO(X) printf("Hello "); printf( X "\n" );</pre>
<p>The problem with this code is, if you want to conditionally run this code with &#8220;if&#8221; this code will not do what you intend to do.</p>
<pre>if(0)
    HELLO("world"); // You'd expect that this HELLO() is never "executed".</pre>
<p>Above code will expand into</p>
<pre>if(0)
    printf("Hello ");
printf( "world" "\n" );</pre>
<p>As you can see in the above example only the first statement in the macro is conditionally executed, this is not what we intended for. Above code will always print &#8220;world\n&#8221;.</p>
<p>So, first thing comes to mind is to put them in curly brackets. Now let&#8217;s evaluate that.</p>
<pre>#define HELLO(X) { printf("Hello "); printf( X "\n" ); }</pre>
<p>Above code looks fine at first glance, but it will also introduce a sneaky bug that will result in compilation error. Now imagine above macro is used like this;</p>
<pre>if(1)
    HELLO("world");
else
    HELLO("baby");</pre>
<p>This will expand into;</p>
<pre>if(1)
{
    printf("Hello ");
    printf("world" "\n");
}; // WE GOT ERROR HERE
else
{
    printf("Hello ");
    printf("baby" "\n");
};</pre>
<p>So, here&#8217;s the trick which works perfectly. It is the <em>do{} while(0)</em> trick. OK, let&#8217;s see.</p>
<pre>#define HELLO(X) do { printf("Hello "); printf( X "\n"); } while(0)</pre>
<p>You can use this as you please, imagine the <em>if else</em> scenario.</p>
<pre>if(1)
    HELLO("world");
else
    HELLO("baby");</pre>
<p>This will expand into;</p>
<pre>if(1)
    do { printf("Hello "); printf( "world" "\n" ); } while(0);
else
    do { printf("Hello "); printf( "baby" "\n" ); } while(0);</pre>
<p>So <em>do {} while(0)</em> does not break when you place a semi-colon after it and also has a scope. So it&#8217;s a ideal for making sure your multiple-statements are executing as you expected.</p>
<p>Well, I guess that&#8217;s all I&#8217;ve got to say.</p>
]]></content:encoded>
			<wfw:commentRss>http://engin.bzzzt.biz/2009/12/12/macros-in-c-the-right-way/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PENSE &#8211; oPEN Simulation Environment</title>
		<link>http://engin.bzzzt.biz/2009/12/06/pense-open-simulation-environment/</link>
		<comments>http://engin.bzzzt.biz/2009/12/06/pense-open-simulation-environment/#comments</comments>
		<pubDate>Sat, 05 Dec 2009 22:03:01 +0000</pubDate>
		<dc:creator>engin</dc:creator>
				<category><![CDATA[stuff i coded]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[fuzzy logic]]></category>

		<guid isPermaLink="false">http://engin.bzzzt.biz/?p=33</guid>
		<description><![CDATA[Now, that I got a IDE/SATA USB case, I started looking at my very old HDDs. I found very old codes of mine, this is one of them. PENSE (oPEN Simulation Environment) was my thesis project. It is a framework which you can use to implement simulation easily. I wrote it in C++. Only dependency is GNU&#8217;s  [...]]]></description>
			<content:encoded><![CDATA[<p>Now, that I got a IDE/SATA USB case, I started looking at my very old HDDs. I found very old codes of mine, this is one of them. PENSE (oPEN Simulation Environment) was my thesis project. It is a framework which you can use to implement simulation easily. I wrote it in C++. Only dependency is GNU&#8217;s libmatheval to implement algorithms out of mathematical expressions easily. I even wrote documentation in LaTeX! :)</p>
<p>Anyway here&#8217;s <a href="http://engin.bzzzt.biz/files/libpense-20050615.tar.bz2">libpense </a>and <a href="http://engin.bzzzt.biz/files/pensedemo-20050615.tar.bz2">pensedemo</a>. Please note the autoconf masterpiece in the libpense :) it was a bitch to get it working but once it is working&#8230; well, it works. I remember compiling these codes on WIN32, Mac OS X and GNU/Linux without a single problem. Yes, I was young and stupid. I developed this on GNU/Linux :)</p>
<p>Oh, the documentation in <a href="http://engin.bzzzt.biz/files/thesis-latex.tar.bz2">LaTeX</a>, <a href="http://engin.bzzzt.biz/files/thesis.pdf">PDF</a> and the presentation in <a href="http://engin.bzzzt.biz/files/presentation.ppt">PPT</a> format is available. Also there&#8217;s a <a href="http://engin.bzzzt.biz/files/refman.pdf">reference manual</a> for libpense, I guess I just had too much time :)</p>
<p>A-hem, and you have to excuse any lameness you can spot, since this is a 4-year old code ;)</p>
<p>A sample code from pensedemo;</p>
<pre>        Environment env;
	Device::Source::PWM pwm( "pwm", &amp;env );
	pwm.setOn( true );
	pwm.setFrequency( pwm_freq );

	Device::Source::VoltageSource vs( 0, 4.8, "voltage source", &amp;env );
	vs.setOn( true );
	vs["output"] = 4.8;

	Device::Plant::DCMotor motor( "Maxon_118465", &amp;env );
	motor.setLoad( "0.0" );
	motor["J_r"] = 0.0000000503;
	motor["k_n"] = 252.374609;
	motor["I_o"] = 0.029;
	motor["V"] = 0.0;
	motor["R"] = 2.16;

	Device::Controller::FuzzyLogic f( 3, "fuzzy logic controller", &amp;env );

	f.setSetPoint( set_point );
	f.setInputDomainWidth( 5 );
	f.setOutputDomainRange( 0, 100 );

        // This is where we connect the devices together to form a feedback loop.
        // We connect the PWM controller to the Voltage Source so that PWM can turn
        // the VS on and off. Then we connect the voltage source to the DC Motor, so
        // that it can, well, run. Then we connect the angular velocity parameter of the
        // motor to the Fuzzy Logic controller, so that it can adjust the PWM controller
        // and control the speed of the motor.
	connect( &amp;pwm, "output", &amp;vs, "on" );
	connect( &amp;vs, "output", &amp;motor, "V" );
	connect( &amp;motor,"w", &amp;f, "input" );
	connect( &amp;f, "output", &amp;pwm, "duty" );</pre>
]]></content:encoded>
			<wfw:commentRss>http://engin.bzzzt.biz/2009/12/06/pense-open-simulation-environment/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Some declaration details for pointers in C/C++</title>
		<link>http://engin.bzzzt.biz/2009/12/03/some-declaration-details-for-pointers-in-cc/</link>
		<comments>http://engin.bzzzt.biz/2009/12/03/some-declaration-details-for-pointers-in-cc/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 09:13:23 +0000</pubDate>
		<dc:creator>engin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[embedded]]></category>

		<guid isPermaLink="false">http://engin.bzzzt.biz/?p=7</guid>
		<description><![CDATA[First of all let&#8217;s remember what a pointer is. A pointer is an address pointing to an object. &#8220;Address&#8221; term is open for debate, some pedantic assess would argue against it.
So let&#8217;s start giving examples.
const char* str ="Foo";
str[0] = 'B'; // error: assignment of read-only location
str = "Bar";  [...]]]></description>
			<content:encoded><![CDATA[<p>First of all let&#8217;s remember what a pointer is. A pointer is an address pointing to an object. &#8220;Address&#8221; term is open for debate, some pedantic assess would argue against it.</p>
<p>So let&#8217;s start giving examples.</p>
<pre>const char* str ="Foo";
str[0] = 'B'; // error: assignment of read-only location
str = "Bar"; // Perfectly OK</pre>
<p>So, it is obvious that first line declares <em>str </em>as n pointer pointing to a constant object and the object is not modifiable but the pointer itself is.</p>
<p>Let&#8217;s review another example.</p>
<pre >char * const str = "Foo";
str[0] = 'B'; // Perfectly OK (See the node below)
str = "Bar"; // error: assignment of read-only variable</pre>
<p>Here we can see that the declaration tells compiler that the pointer value (address) is constant but the object it is pointing to can be modified. Please note that even though the above assignment &#8220;str[0] = &#8216;B&#8217;&#8221; will compile just fine, it will most probably result in a segmentation fault during runtime since your compiler will most likely put it in read only memory region.</p>
<p>Now let&#8217;s make another example.</p>
<pre>const char * const str = "Foo";
str[0] = 'B'; // error: assignment of read-only location
str = "Bar"; // error: assignment of read-only variable</pre>
<p>This declaration tells the compiler that neither the object the pointer is pointing to can be modified, nor the pointer value (address) itself. i.e. nothing is modifiable :)</p>
<p><strong><span style="text-decoration: underline;">Conclusion</span></strong></p>
<p><strong>So, we can conclude that qualifiers (const, volatile) that are placed before the * applies to the object the pointer is pointing to, and qualifiers placed after the * applies to the pointer value itself, i.e. the address.</strong></p>
<p>So we can have weird looking declaration like this one:</p>
<pre>extern volatile const char * volatile const str = "Foo";</pre>
<p>I know it looks a bit unusual but it is perfectly valid.</p>
<p>Note: For hardware programming volatile keyword is a must. If you don&#8217;t know what it is, read this <a title="what is volatile keyword used for" href="http://wiki.answers.com/Q/Volatile_example_code_sample_coding_of_volatile_pointer">article</a> at wiki.answers.com first. Here&#8217;s the <a href="http://backupurl.com/ksfqr7">backup</a>, just in case.</p>
]]></content:encoded>
			<wfw:commentRss>http://engin.bzzzt.biz/2009/12/03/some-declaration-details-for-pointers-in-cc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

