Jolt Cola is back!

The legendary soda with “all the sugar, and twice the caffeine” is back! The soda, which first became available in 1985, went off the market around 2009. By that time, it had evolved away from the original cola, and was being sold as an energy drink in large cans that resembled AA batteries.

You can currently only find Jolt Cola at Dollar General Stores, or on Amazon. At Dollar General, it will be in the “valley of values” aisle, rather than with the other sodas or energy drinks. The best part is, the price for the larger 16 ounce cans is just $1. You can find out if your local Dollar General has them by visiting the map at:

Http://www.joltcola.com

On Amazon, you will be paying around $3 a can, shipped right to your doorstep.

Exciting news for 2018! More details later…

Sub-Etha Software to attend 2018 Chicago CoCoFEST!

FOR IMMEDIATE RELEASE:

Sub-Etha Software to attend 2018 Chicago CoCoFEST!

Des Moines, Iowa – January 11, 2018 – Iowa-based Sub-Etha Software has announced plans to attend the 2018 27th Annual “Last” Chicago CoCoFEST! The event will be held April 21 and 22, 2018 at the Heron Point Convention Center in Lombard, Illinois.

“We’ve missed a number of years over the past decade or so, but we don’t plan to miss this year,” says Sub-Etha co-founder and current operator, Allen Huffman. “Missing these shows sucks. And this year we don’t want it to suck.”

Sub-Etha Software plans to demonstrate Roger Taylor’s “CoCo on a Chip” FPGA project, as well as a few “vaporware” items from the company’s past, including the CoCo-VR project and CoCo Answering Machine project.

A selection of N.O.S. (new old stock) Sub-Etha items may be available on (probably unreadable) 5 1/4″ floppy disks in original (“vintage”) packaging.

There will not be any Jolt! Cola, because that no longer exists. And there might even be Jolt Cola, because thanks to a tip from L. Curtis Boyle in the comments, it went back in to production in late 2017!

About Sub-Etha Software

Sub-Etha Software was founded in Lufkin, Texas in 1990, as a partnership between Allen C. Huffman and Terry S. Todd. It made it’s first CoCoFest appearance at the First Annual Atlanta CoCoFest in 1990, and it’s first Chicago CoCoFest appearance at the First Annual “Last” Chicago CoCoFEST! in 1992. They may be contacted online at www.subethasoftware.com

About the Chicago CoCoFEST!

The 27th Annual “Last” Chicago CoCoFEST! is sponsored by the Glenside Color Computer Club of Illinois. They may be contacted online at www.glensideccc.com.

Contact:
Allen Huffman
alsplace@pobox.com
PO Box 7634,
Des Moines, Iowa
U.S.A.
Ph: 515-999-0227

###

Personal OS-9 to return?

According to a post made today by Allan Batteiger in the Microware OS-9 public group on Facebook, we may finally see the return of a version of OS-9 for hobbyist use.

The message announced the pending release of OS-9/68K to version 4.0, and OS-9 for ARM, PowerPC and X86 to version 6.1. Notable updates including an new networking stack supporting IPv6, and updates to OPENSSL. He also mentioned work to get the CLANG/LLVM compiler generating code for OS-9 PowerPC and ARM, with an alpha release coming later this year.

Of interest to the hobbyist community:

“Work has been proceeding on the OS-9 for Makerspace. We now have USB & Networking working on the Raspberry Pi 1 & 2 boards. Work has started on the Raspberry Pi 3. Also work is moving forward on the BeagleBone Black and Asus Tinker boards. The plan is to release preliminary versions of the Makerspace OS-9 yet this year.” 

For those of us who used to run OS-9/6809 on the Radio Shack Color Computer, or OS-9/68K on systems like the MM/1, this is pretty exciting news. A low-cost Raspberry Pi could be very fun to play with, though it would be missing the advanced terminal and screen controls that we had under OS-9 Level 2 (CoCo) and K-Windows (MM/1). To me, porting that functionality would be one of the first projects we should undertake.

Exciting news!

Revisiting Rainbow magazine.

Happy 2018!

Can you believe this year will mark 38 years since Radio Shack released the TRS-80 Color Computer (later nicknamed the “CoCo”)? According to the always reliable wikipedia, the Color Computer was announced on July 31, 1980. According to a calendar printed in the July 1987 issue of Rainbow magazine, the CoCo was introduced (made available for sale?) on August 20th that same year:

August 1987 Rainbow, anniversary souvenir calendar: “August 20 – Radio Shack introduces the 4K TRS-80 CoCo for $399. First computer to offer easy graphics and  sound programming from BASIC. 1980”

That date always stuck with me because it is my birthday. Too bad I didn’t know anything about computers in 1980, else I might have asked for one. Instead, I didn’t get switched on to computers until a few years later, with my first machine being a Commodore VIC-20 (“the first full featured color computer for under $300”) in 1982.

In my early days of owning a computer, I also owned some computer magazines. I remember Family Computing, COMPUTE! (wow, they published in until 1994), and later COMPUTE!’s Gazette, which focused on the Commodore VIC-20 and 64 (wow again, for them publishing until 1995). Somewhere I still have a box with all my old magazines in them.

When I switched from VIC-20 to Color Computer in 1983, I was still able to make use of some of those early magazines that contained CoCo versions of program listings. I remember being annoyed at seeing the CoCo version rely on BASIC’s single-note “PLAY” command for music, while they had to use assembly language routines to do the same on the Apple 2. If they were using assembly code, they could have done the same on the CoCo and gotten 4-voice harmony music out of the machine! But instead, that “easy graphics and sound programming from BASIC” must have made sticking with one-voice music the easier path. I think that always made the CoCo versions look worse than they had to.

Shattered by a Rainbow

At some point, I learned about an all-Color Computer magazine called The Rainbow. I think my first copy of Rainbow was the November 1983 “Data Communications” issue. I’ll have to dig out my storage box and see how well my memory has held up over the past 35 years!

In a way, it destroyed some of my hopes and dreams. When I made the decision to get a CoCo, part of the reason was because of the small selection of software Radio Shack sold for it. I thought, with such a small software base, it would be a great system to program for! I could become rich in such a desolate marketplace!

The 300+ pages of Rainbow, full of program listings and ads for hundreds of software and hardware items, made me give up those dreams. Looking back, I wish I hadn’t. The market was large enough for some programmers to make their living off of it. Even in the late 1980s, I heard about one shareware programmer who helped pay his way through college by writing CoCo software!

In addition to Rainbow, I also learned about two other CoCo-only publications. Color Computer Magazine was published from March 1983 to October 1984. There was also Hot CoCo (Wayne Green Publications), which lasted a bit longer, publishing from June 1983 to February 1986. (Those links lead to full scans of all the issues over at the Color Computer Archive site.)

Although I did buy a few issues of Color Computer and Hot CoCo, the only one I subscribed to was The Rainbow. As a junior high school student, I didn’t have the income for multiple subscriptions, though I wish I had – I expect I would have benefited from the other two publications.

I chose Rainbow because it was the largest. In December 1983, Hot CoCo had 148 pages, Color Computer Magazine had 146 pages, and Rainbow was larger than both of them put together at 340 pages!

I could read through the two smaller ones, and probably find an article of of interest, but Rainbow always seemed to have dozens of things I liked. If I could only afford one, it just made sense to go for the biggest. (At the time, Rainbow was more expensive, with a cover price of $3.95 versus $2.95 for the other two.)

Back to the Beginning

Sometime in early 1985, I must have been contemplating completing my collection of Rainbow because I decided to order a back issue of the first issue from July 1981. I think I spent $2.00 or so for the issue, plus $3.50 postage and handling.

Imagine my disappointment and surprise when it arrived and it was a photo copy of two sheets of paper, printed doubled sided by a dot matrix printer that didn’t even have true descenders for lowercase!

Could this be? Did this nearly-400 page behemoth of a magazine with it’s glossy, full color cover really start out as a two page newsletter?

Indeed it did!

But rather than complain, I ended up writing in to The Rainbow and suggested that reprinting this early issue inside the magazine would be a neat thing to do. In the July 1985 anniversary issue, they printed my letter and included a reproduction of that original two page newsletter:

August 1985 Rainbow, letters to the editor.

Editor:
I have an idea for your upcoming anniversary issue that you may like. I was told that THE RAINBOW started off as ·a two~page newsletter. Since many CoCo owners were not a part of that beginning, me included, I thought it would be nice to
see some reprints of the “early RAINBOW.” You may not think this is a big deal, but I would be more than happy to see how the # 1 CoCo magazine got its start. I think others share this curiosity as well as I do.
Allen Huffman
Broaddus, TX

Editor’s Note: Great idea, Allen. So, for Allen and all of you helping us celebrate our fourth anniversary, we’ve reprinted our very first Issue in its entirety in this issue (see between pages 98 and 99) – a little birthday treat from all of us to all of you!

I think I had at least two other letters printed in the magazine, but this was the one I was most proud of. (Notice my little white lie about “I was told that…”  I knew darn well it was a two page newsletter because I felt ripped off paying over five bucks to get a copy of it!)

Let’s do the time warp, again!

The days of monthly magazines with computer programs you could type in is long gone. But, the history of them has been preserved thanks to the efforts of folks willing to scan in old paper and make it available online for a new generation to discover (or for us old folks to use to relive our younger years).

You can find issues at Archive.org, but I think the best collection is at the previously-mentioned Color Computer Archive site:

Rainbow, The (Searchable Image)

That link will take you to a repository that contains scans of every issue of Rainbow, from the original two page newsletter in 1980, to the largest of the glossy magazine editions, down to the final newsprint issue of May 1993. Some scans are just images of the pages, but the above link had been OCR’d so you can do text searches on it (mostly).

Until these archives, I had only seen the issues that I owned, from November 1983 to sometime around 1991. I recall ending my subscription in protest because Rainbow had decided to not cover any of the “next generation” CoCo-style machines such as the MM/1. Looking back, that was something I regret. Had we all kept subscribing and supporting them, maybe they could have continued a few years longer.

With all of this said, I have decided to start an interesting project. I plan to read all the issues of Rainbow, starting with July 1981. I’ve actually made it through the first six issues, where it grew from two photocopied pages into the first “magazine style” issue with 19 pages in December 1981.

And boy is it a time travel experiment! It’s stunning to see the tiny thing that birthed the magazine I loved so much.

If you are looking for some retro reading for 2018, why don’t you join me? I bet we (re)learn many things over the course of the year.

It’s quite interesting reading news about Radio Shack working on a “disc system” for the Color Computer, and then reading a review of this new $600 add-on a few issues later. That, and all the mentions of COLOR BASIC, and why you might want to upgrade to 16K or 32K and EXTENDED COLOR BASIC, really take you back to an earlier time.

And I have yet to see the name “CoCo” used. That would come later.

I’ll share interesting tidbits as I run across them. I’m sure I will learn quite a bit about the early years before I was involved.  Maybe you will to.

Until next time…

A Time Travel Experiment: The retro newsletter project proposal

The internet is an interesting place. Quite often, things I am trying to find end up not findable (far too often), but I almost always end up somewhere I didn’t intend to be finding something I didn’t mean to find.

Recently, I went in search for a Chromaset game that was referenced by L. Curtis Boyle on CoCoTalk Live (the nation’s leading weekly Color Computer talk show) episode 17. A reference had been made to this “Zero Gravity” (I think that was the title) game being disassembled and ported to OS-9, and I was curious to see what kind of game it was.

During this search, which was unsuccessful, I ended up at some random home page that had an archive of newsletters in PDF format. The one I found was from 1983, and it contained a review of the Chromaset subscription service (which I think was a cassette tape full of programs you received each month).

It was a fascinating read, including an article talking about rumors that Radio Shack was working on a “CoCo III” model. (That article was a gag, though, but no doubt rumors of a CoCo 3 must have started circulating as soon as the CoCo 2 came out.)

Reading through this newsletter was like stepping back in time. 1983 was when I received my first Radio Shack Color Computer. I remembered newsletters like this.

Today, archive sites like archive.org and the Color Computer Archive do a great job at trying to preserve much of this old information. I have scanned and submitted several newsletters and manuals, myself. One could easily spend weeks going through all that is there, which is why I expect none of us have done it. (I wasn’t even aware of this “ETUG” newsletter until I stumbled on it accidentally.)

Wouldn’t it be neat…

With retro computing so popular these days, wouldn’t it be neat if there were some kind of subscription service that would mail you physical paper copies of newsletters from the past, on a schedule just like they were back then? I’m not talking about anything new, but actually representing a point in time as if you were subscribing to them back then.

All it would take is finding as many of these newsletters as possible and getting them organized by date. Then, when someone subscribed, they’d start receiving newsletters each month, starting with the earliest time available.

Or, you could sign up starting at a specific month (say, the year you first got your computer).

Subscribers wouldn’t be in sync with each other, so discussing the “latest” news would be problematic, but since all of this exists digitally, it would be as simple as…

Hey, I just got the August 1983 issue of CoCo Chronicles out of East Texas. There’s this cool BASIC program that makes sound like a synthesizer with no machine code! Here’s a link to the PDF of the issue

Think of all the great tips and programs we’d (re)discover this way, as a new generation wades through the cutting edge information of 35 years ago.

There might even be a way to automate something like this, through a service that will print and mail on demand.

Sure, we can all go download any of these for free… But have we? It’s much easier to pay attention to something when it shows up at your house, versus you having to remember to go out and find it. (Amazon, anyone?)

There are some problems, of course: Copyright. Low quality scans of copies that might be hard to read. Zero interest in this…

But if such a service existed, would you sign up? How much would you be willing to pay? Who would have the time to run something like this?

Discuss.

C musing of the day: i++ or ++i?

Here’s another short side-musing about C…

At my previous job, I did embedded programming on TI MSP430, PowerPC and Renesas processors. We were in the process of moving to a new system based on ARM architecture. It was during this time that I went from being part of a tiny local team to being part a much larger group spread out around the world.

But I digress.

On this team were some great minds, and one of them produced a document listing a bunch of optimizations we could do in our code to reduce size and/or improve speed. I wish I had a copy of it as it would be fun to discuss the suggestions here and get some feedback. But for today, I’ll bring up one that was just brought up by a coworker at my current job.

var++ versus ++var

I am very used to writing (and seeing) variable increments written like this:

i++;

Is it called a post increment, I believe. There is another version called pre-increment that looks like this:

++i;

By themselves, the result appears the same. For example:

int i;

i = 0;
printf("i = %d\n", i);
i++;
printf("i = %d\n", i);

That would print 0, then i++ would increment it, then it would print 1.

int i;

i = 0;
printf("i = %d\n", i);
++i;
printf("i = %d\n", i);

That would print 0, then ++i would increment it, then it would print 1.

The reason there is pre and post is for situations where you want to check something at the same time you increment it. If you use “i++” in a check…

i = 0;
if (i++ == 1) printf("This will NOT be printed.\n");

…it checks the value of “i” , then increments it after the check (post increment, see?). But if you go the other way:

i = 0;
if (++i == 1) printf("This WILL be printed.\n");

…it increments “i” first, then checks the new value of i.

Behind the scenes, “i++” has to do more work since it has to retain the original value of i for the compare. I think a post-increment might look something like this:

i = 0;    // SET i TO 0
if (
    i++   // SAVE VALUE OF i AS TEMP_i
          // INCREMENT i
    == 1) // COMPARE TEMP_i TO 1

And a pre-increment might look like this:

i = 0;    // SET i TO 0
if (
    ++i   // INCREMENT i
    == 1) // COMPARE i TO 1

If all you are JUST wanting to increment (or decrement) a variable, it might make sense to always use the pre-increment version (“++i”) so the extra “save this value for later” code is not produced.

BUT, a good compiler optimizer should be able to see that nothing cares about that temporary value and just discard it rather than building it in to your binary.

With a good optimizer, it shouldn’t make any difference. But perhaps it’s better to write it like you mean it since “if (i++ …” means something different than “if (++i …”.

But geez, after twenty years of writing “i++” it sure would be hard to switch.

Does it matter? What if I am writing for an old pre-ANSI K&R compiler?

Comments appreciated.

C musing of the day: signed ints

I ran across some code today that puzzled me. It was an infinite loop that used a counter to determine if things took too long. Something like this:

int main()
{
  int count;
  int status;

  count = 0;

  do
  {
    status = GetStatus();

    count++;

  } while( status == 0 );

  if (count < 0)
  {
    printf("Time out! count = %d\n", count);

    return EXIT_FAILURE;
  }

  printf("Done. count = %d\n", count);

  return EXIT_SUCCESS;
}

The code would read some hardware status (“GetStatus() in this example)  and drop out of the do/while loop once it had a value. Inside that loop, it increments a count variable. After done, it would check for “count < 0” and exit with a timeout if that were true.

Count is only incremented, so the only way count could ever be less than zero is if it incremented so high it rolled over. With a signed 8-bit value (int8_t), you count from 0 to 127, then it rolls over to -128 and counts back up to 0.

So with an “int” being a 32-bit value (on the system I am using), the rollover happens at 2147483647.

And that seems like quite a weird value.

But I suppose it it took that long, it certainly timed out.

I think if was going to do it, I would have probably used an unsigned integer, and just specified an appropriate value:

unsigned int count;

...

if (count > 10000)
{
  printf("Time out! count = %u\n", count);
  return EXIT_FAILURE;
}

What says you?

C warnings, %d versus %u and more C fun.

Code cleanup on aisle five…

I recently spent two days at work going through projects to clean up compiler warnings. In GNU C, you can enable options such as “-Wall” (all warnings), “-Wextra” (extra warnings) and “-Werror” (warnings as errors). By doing steps like these, the compiler will scream at you and fail to build code that has warnings in it.

Many of these warnings don’t impact how your code runs. They just ask you “are you sure this is what you are meaning to do?”

For example, if you leave out a “break” in a switch/case block, the compiler can warn you about that:

  x = 1;

  switch( x )
  {
  case 1:
    printf("x is one\n");
    // did I mean to not have a break here?

  case 2:
    printf("x is two\n");
    break;

  default:
    printf("I don't know what X is\n");
    break;
  }

This code would print:

x is one
x is two

…because without the “break” in the “case 1”, the code drops down to the following case. I found several places in our embedded TCP/IP stack where this was being done intentionally, and the author had left comments like “/* falls through below */” to let future observers know their intent. But, with warnings cranked up, it would no longer build for me, even though it was perfectly fine code working as designed.

I found there was a GCC thing you could do where you put in “//no break” as a comment and it removes that warning. I expect that are many more “yes, I really mean to do this” comments GCC supports, but I have not looked in to it yet.

Size (of int) matters

Another issue I would see would be warnings when you used the wrong specifier in a printf. Code might compile fine without warning on a PC, but generate all kinds of warnings on a different architecture where an “int” might be a different size. For example:

int answer = 42;
printf("The answer is %d\n", answer);

On my PC, “%d” can print an “int” type just fine. But, if I had used a “long” data type, it would error out:

long answer = 42;
printf("The answer is %d\n", answer);

This produces this warning/error:

error: format '%d' expects argument of type 'int', but argument 2 has type 'long int' [-Werror=format=]|

You need to use the “l” (long) specifier (“%ld”) to be correct:

long answer = 42;
printf("The answer is %ld\n", answer);

I found that code that compiled without warnings on the PC would not do the same on one of my embedded target devices.

%u versus %d: Fight!

Another warning I had to deal with was printf() and using “%d” versus “%u”. Most code I see always uses %d, which is for a signed value which can be positive or negative. It seems works just fine is you print an unsigned integer type:

unsigned int z;

z = 100;
printf("z is %d\n", z);

Even though the data type for z is unsigned, the value is positive so it prints out a positive number. After all, a signed value can be positive.

But, it is more correct to use “%u” when printing unsigned values. And, here is an example of why it is important to use the proper specifier… Consider this:

#include <limits.h> // for UINT_MAX

unsigned int x;

x = UINT_MAX; // largest unsigned int

printf("x using %%d is %d\n", x);
printf("x using %%u is %u\n", x);

This prints:

x using %d is -1
x using %u is 4294967295

In this case, %d is not giving you what you expect. For a 32-bit int (in this example), ULONG_MAX of 4294967295 is all bits set:

11111111 11111111 11111111 11111111

That represents a -1 if the value was a signed integer, and that’s what %d is told it is. Thus, while %d works fine for smaller values, any value large enough to set that end bit (that represents a negative value for a signed int) will produce incorrect results.

So, yeah, it will work if you *know* you are never printing values that large, but %u would still be the proper one to use when printing unsigned integers… And you won’t get that warning :)

C warning: comparison between signed and unsigned integer expressions [-Wsign-compare]

Trick C question time … what will this print?

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int x;
  unsigned int y;

  x = -1;
  y = 2;

  printf("x = %d\n", x);
  printf("y = %u\n", y);

  if ( x > y )
  {
    printf("x > y\n");
  }
  else if (x < y)
  {
    printf("x < y\n");
  }
  else
  {
    printf("x == y\n");
  }

  return EXIT_SUCCESS;
}

I recently began looking in to various compiler warnings in some code I am using, and I found quite a few warnings about comparing signed and unsigned values:

warning: comparison between signed and unsigned integer expressions [-Wsign-compare]

I thought I could safely ignore these, since it seems plausible to compare a signed value with an unsigned value. A signed value of -42 should be less than an unsigned value of 42, right?

In the above example, it will print the following:

x = -1
y = 2
x > y

Nope. I was wrong. According to C, -1 is greater than 2.

C does something that I either never knew, or knew and have long since forgotten. I guess I generally try to write code that has no warnings at all, so I’ve avoided doing this. And now I know (or re-know) the reason why.

When dealing with mis-matched comparisons, C makes them both unsigned. Thus, “-1” becomes whatever -1 would be for that data type.

char  achar  = -1;
short ashort = -1;
int   aint   = -1;
long  along  = -1;

printf("char  -1 as unsigned: %u\n", (unsigned char)achar);
printf("short -1 as unsigned: %u\n", (unsigned short)ashort);
printf("int   -1 as unsigned: %u\n", (unsigned int)aint);
printf("long  -1 as unsigned: %u\n", (unsigned long)along);

This outputs:

char  -1 as unsigned: 255
short -1 as unsigned: 65535
int   -1 as unsigned: 4294967295
long  -1 as unsigned: 4294967295

Thus, on a PC, an 8-bit signed value of -1 is treated as a 255 when comparing against an unsigned value, and a 16-bit as 65535. It seems an int and long as both 32-bits on my system, but these could all be different on other architectures (on Arduino, and int is 16-bits, I believe).

So, without this warning enabled, any comparison that looks correct might be doing something quite wrong.

Warnings are our friends. Even if we hate them and want them to go away.

 

const-ant confusion in C.

Updates:

  • 2017-11-30 – Fixing description of MyStructure example. Thanks, Lost Wiz!

Embedded Life

I currently make my living doing embedded C programming. I am not quite sure how to define what “embedded” programming is other than to say: you probably don’t have everything you expect.

You often program on systems without file systems, without gigabytes of RAM and without an operating system to do most of your work for you. For example, at my previous job one of my main platforms (a TI MSP430 processor) had only 10K of RAM and the program was limited to 40K of flash storage. At my current job, I work on several variations of ARM processors, with one configured to give me only 7K of RAM and 36K of program space.

These systems are much closer to an Arduino UNO, which has 32K of flash and 2K of RAM, than a desktop Windows or Linux machine.

Not all embedded systems are this tiny, of course. There are many embedded systems that run Linux, but once you have a full operating system and a file system, the definition of “embedded” seems to be used to just mean “smaller than Windows”.

But I digress…

Over the past six years, I’ve worked on code that was created and maintained by many different programmers before I worked on it. I have learned some cool tricks and also seen some very un-cool tricks (i.e., just wrong). I expect I will be leaving my own cool/un-cool bits of code for future programmers to find.

With that said, there is one item that keeps turning up repeatedly that many of us C programmers don’t seem to really understand because we keep misusing it. And by “we” I include myself.

“const”

There is a keyword in C called “const” which, according to Wikipedia, “indicates that the data is read only.” For example, suppose you wrote a function that accepts a string (actually, pointer to a bunch of characters) like this:

void PrintErrorMessage( char *message )
{
  fputs( "ERROR: ", stderr );
  fputs( message, stderr );
}

In this example, whatever string passed in will be displayed with “ERROR: ” prepended to it.

int main( int argc, char **argv )
{
  PrintErrorMessage("File Not Found");

  return EXIT_SUCCESS;
}

That would display a message to standard error output:

ERROR: File Not Found

But, there is nothing preventing the function from trying* to modify the string that was passed in.

* Key word is “trying”… If that string were embedded in the binary and it was running out of ROM or Flash, attempts to modify it would be rejected by the “hardware can’t do that” exception ;-)

void PrintErrorMessage( char *message )
{
  fputs( "ERROR: ", stderr );

  // Convert message to uppercase
  for (int i=0; i&lt;strlen(message); i++)
  {
    message[i] = toupper(message[i]);
  }
  fputs( message, stderr );
}

The intent here would be to display the error message in uppercase, such as “ERROR: FILE NOT FOUND”. This would work if the string being passed in was modifiable, such as:

char message[80];

strcpy(message, "File Not Found");
PrintErrorMessage( message );

…but after returning from that call, the string would have been modified by the function and would now be “FILE NOT FOUND” in memory. This is fine, if that is the intent of the function, but if you do not intend the string to be modified, you can take steps to prevent the function from being able to do it.

Only read this…

“const” will tell the compiler to not allow code to be built that modifies the variable. You see it used all the time by standard C library functions that take strings, such as puts(), strcpy(), etc.

int puts ( const char * str );

For puts() and similar functions, the use of const disallows modifying that string within the function. In the earlier example, we could make the passed-in string “read only” like this:

void PrintErrorMessage( const char *message )
{
  int i;
  fputs( "ERROR: ", stderr );

  // Convert message to uppercase
  for (int i=0; i&lt;strlen(message); i++)
  {
    message[i] = toupper(message[i]);
  }

  fputs( message, stderr );
}

With that change made, the compiler now should issue warnings (or errors) on attempts to modify the “message” string inside the function:

error: assignment of read-only location '*(message + (sizetype)((unsigned int)i * 1u))'|

The moment the function tries to modify “message[i]” causes a problem, because “const” has told the compiler whatever is passed in should not be modified.

Because of the usefulness of this extra compile-time error checking, const is a good thing to use.

And many of us do.

Incorrectly.

There is a bit of confusion in how const works. In the above example, we pass in the pointer to some memory that contains a string. We do not want the memory that is being passed in to be modified, so we use “const char *message”. According to the “C Gibberish” website, that means:

declare message as pointer to const char

We might also want to prevent the pointer itself from being modified by using “const char const * message” … and that would be incorrect. That is not the proper syntax for “const”:

declare message as pointer to const const char

The confusion comes from const allowing two ways of doing the same thing. Did you know that:

const char

…is the same as:

char const

In C, the true syntax seems to be using “const” after the thing you are declaring, like “char is a constant” or “* is a constant”. But, at the start of that line, const can be used at the beginning to mean the same thing, and since we see that all the time, many of us seem to think that const describes what comes after it. Which it doesn’t.

To properly declare that the pointer and the data it points to should be read-only, it should be:

char const * const message;

C Gibberish agrees:

declare message as const pointer to const char

We need to learn this double “before or after is the same thing” use, or only use the “after” use and be consistent.

// declare message as const pointer to const char
const char * const message;

is the same as

// declare message as const pointer to const char
char const * const message;

My most recent encounter with this was in code at work that did something like this:

void Initialize(const MyStructure *config);

They must have intended this to mean “I’m passing in a constant MyStructure pointer which cannot be modified” but, in reality, what they were getting was:

declare config as pointer to const struct MyStructure

They were telling the compiler that the structure being pointed to was read-only and should not be modified. But the function’s purpose was to modify elements of that structure:

config->type = 10;
config->foo = 'a';

Because of this misuse of const, many compiler warnings were generated.

||=== Build: Debug in Const (compiler: GNU GCC Compiler) ===|
main.c||In function 'Initialize':|
main.c|16|error: assignment of member 'type' in read-only object|
main.c|17|error: assignment of member 'foo' in read-only object|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

The fix was to correct the prototype and function to do what was actually intended:

// declare config as const pointer to struct MyStructure
void Initialize(MyStructure * const config);

This now disallows the “config” pointer from being changed, but not the structure it points to. Thus, this would not work:

config++; // Increment config pointer.

…but the intended structure modifications would:

config->type = 10;
config->foo = 'a';

I’m sad to say I’ve been using “const” incorrectly as long as I can remember using “const.”

For a future article, I may dive in to some deep const-ant confusion I recently found myself in, and see if someone out there can tell me if I am finally doing it correctly or not.

Until then…