Monday, December 8, 2008

The ACM-ICPC Experience

As this year’s ACM ICPC Regionals played out in front of us, our road to the ICPC world finals seemed to run into a dead end. Despite the failure, I feel obliged to put this one down in my blog, a permanent record of how and what happened, though I’m pretty sure I’m not going to forget any of the details any time soon.

For the uninitiated: The ACM ICPC is one of the most coveted programming competitions for college students. ACM stands for Association of Computing Machinery, and is the world’s largest educational and scientific computing society. ICPC is short for International Collegiate Programming Competition. The ICPC is open to contestants from all over the world who happen to be studying in colleges, during the prime of their algorithmic lives. There are 5 regions, Asia, Africa and the Middle East, Europe, North America and South Pacific. Contestants are to compete in teams of three, with a coach, and an optional reserve candidate, and take part in an online round, to qualify for the onsite regional finals. The top two to three teams from each region compete in the world finals.

Suren, Nutty and I had qualified to take part in the regional finals, to be held at Amrita Vishwa Vidyapeetham, Amrita University, Amritapuri Campus, Kollam, as team LRSL (Last Row of Sun Lab: something of a cult back in college). I don’t think I’d be speaking for myself when I say what followed were an amazing four days that left us with memories of a lifetime.

Day 1

We were supposed to check in at Amrita on Day 1. Nutty had made his way to campus by himself. Suren came over to my place in the morning, and we left for the college by train in the evening. Not having travelled along this route for a long time, I was quite excited at the prospect of a train ride through the beautiful green countryside of Kerala. The speed of the trains plying on this route adds to the fun.

We arrived at Karunagapalli Railway Station at around 6:45pm where a car was waiting for us. We hopped on, and made casual conversation with the volunteer who had come to pick us up, as we sped to the campus. None of us had ever been here before, and had no idea what to expect. We were met with a warm reception, a host of cheerful volunteers who made it clear they were there to help, and a college adorned with banners, balloons, and tapestry, all exuding the idea that something big was coming up, and something big certainly was.

We completed the registration process, and were handed a bag of goodies, a notebook, a pen, a bunch of brochures and texts related to the college and ICPC, and a lovely ICPC T-Shirt, and were then led away to our room.

The hostel we were meant to stay in was as good as a lodge. The door of our room bore an ICPC label that brandished our team name and institute. A comfortable room, furnished with sleek cupboards, tables and cots, clean mattresses, the softest pillows and long blankets you could wrap yourself in like a candy, and a bottle of water for each inmate, we seemed to have everything we ever wanted.

Day 2

Our first full day in the college, Suren and I took in the complete picture of what our hosts had done to the college for our visit. Majestic ACM ICPC banners proclaiming the battle of the brains that loomed in the near future livened up the hallways. The pillars bore balloons of blue, yellow and red. Twenty-five foot leaves of ICPC colors hung from a disk suspended in the middle of the quadrangle of the college’s main building. The quadrangle was further decorated with two foot dice, and two dozen B, Y and R balls.

We were given the official welcome in the traditional Keralite style, with a volunteer applying chandan, followed by a thalappoli (a path marked by beautiful girls wearing saris and holding oil lamps on either side) leading into the college main building, and panchavadyam (music using five different instruments, although I didn’t care to count) in the background.

Breakfast, lunch, evening snacks and dinner were served at the campus canteen, modified into a makeshift mess for the ICPC contestants. Food was exquisite, and I ate a whole day’s worth for each meal. They followed a buffet system, and never before had I seen such a variety of rich food on my plate during breakfast, or gone for thirds for lunch, or enjoyed a purely vegan dinner so as to fill myself up till my vision blurred.

We used to get idiappams, appams, uppuma etc. for breakfast, along with as many slices of bread as we pleased, with jam, and the best butter served as cubes, followed by a bowl of corn flakes with milk, and tea or coffee (poor Suren couldn’t have any of these, due to his hostilities with milk). Lunches were topped off by delicious curries and one variety of payasam every day. The tea alone was sufficient reason to show up for snacks at five. Dinners saw roti and either fried rice or pulao, with dal, gobi, paneer and mushroom dishes to go along, hardly leaving space in our tummies for dessert, mostly ice creams, fruit salads and juices. Fruits were served regularly with lunch and dinner.

We had two practice contests on Day 2, one in the morning, and the other later in the night, after supper. Practice contest problems were pretty simple, and quite rightly so: practice time is meant to get yourself used to the environment, and work out different specifications, such as how much memory and stack space your code is allowed, how many instructions the judge machine can run per second, what warnings are treated as errors, and what warnings are ignored, what libraries are allowed and so on. Both contests were supposed to have the same problems, so we went for just one, got all the specs we needed, and left after submitting both problems.

In the afternoon, we had a beach trip. The previous day, during the registration process, we were given the choice of either going to the beach, or playing in a variety of indoor games, such as chess, carroms, and badminton. We pretended to consider our options for a while, though we had telepathically debated the issue, and decided on the beach trip even before the question was complete. Beaches are always most fun when you have people your same age and intentions all around you. There were five teams from my college, so there was no lack of friends to make merry with. This beach was one of those remote not-commercialized-yet getaways we urban folk dream of. The water was pure, and the sands were free of the usual plastic and paper wastes we normally find at the most famous beaches around the country. Get wet we did, though I had to hold back a bit for fear of taking ill before the contest.

We also had the formal inauguration ceremony. Nothing unusual there, it was just a few speeches followed by a mohiniattam by a student of the host college. We got to look around and see all the big brains from around Asia gathered there. Among the people that caught my attention would be a bunch of students from Singapore, a coach from Kazakhstan that seemed to move around like a short circuited robot (although a lot of girls were tailing the guy the next couple of days, so I have something to be jealous of), and a funny looking girl from Bangalore (I think, my intelligence sources are questionable) that keeps spotting me every time I look at her (and this continued as a vicious circle till we left, me, looking at her to see if she’ll spot me again, and she, spotting me looking at her).

The Big Day

The contest was scheduled for 8:00am on the third day. We got up early, quite against tradition, freshened up and trotted off for breakfast. I was feeling the pressure then, struggling with my food and having second thoughts about the amount of sugar in the corn flakes. To make matters worse, we ran into The Great P, intimidating, as a God watching over a battle of mere mortals.

The contest environment was grand. Good computers with my favorite DELL keyboards, with Ubuntu 8, and with just two teams in every row, giving you sufficient space to move about to let out steam to keep your head from overheating. The computers for each team’s use were marked up by a small radio sized pyramid bearing the ICPC logo and the team name on it. Each time a team gets a problem right, a volunteer comes along and attaches a balloon to the pyramid, so that at any point of time, you could just look around to get an idea of how the other teams are dealing with the contest. The balloons would also be of the same color as the color code for the problem, so you can also see which problems are being solved the most, without looking at the ugly percentages in the statistics page. Of course, I was quite confused why the volunteers were giving us fewer balloons than everybody else, and needed Nutty’s help to figure it out.

Supposedly being the best coder (in terms of speed, correctness, etc., nothing to do with skill) in the team, I was given the responsibility of implementing the solutions my teammates came up with. I’m not sure whether I had wanted to do well, and I was worried if I could, or whether I was simply scared of making mistakes and letting my teammates down, but that’s exactly what I did.

I had a shaky start, having trouble implementing the easiest problem of the lot. After half an hour of toil, I finished the code, and submitted it, and thankfully got it right. We were in a good position then; even after what I consider one of my slowest and sloppiest pieces of work, it seems most teams submitted the problem after us, either because they were having the same kind of trouble, or because they saw the problem later.

I messed up our second problem with two wrong submissions, racking up 80 minutes of penalty time, before managing to get it right. I was getting up to speed: even with two wrongs, we were looking good amongst the other teams who got around to completing their second one eventually. Most of the other problems were tough, and they made the difference between the best and the rest. The top team got seven correct, while second, third and fourth managed six. We were down in twenty fifth, a good start at ICPC, but not good enough, at least in my view. All five teams from our college were separated by less than a dozen or so ranks. I was gloomy, and wasn’t very social, to say the least. I didn’t respond to chat all afternoon, though I’m not the least bit apologetic: my status message clearly said I wasn’t in the mood, except for the choicest few.

By evening, I was feeling better, and so was everyone else. We went for tea, and by the time we made it to the auditorium, the presentation ceremony had started. Luckily we got there before our team’s turn came, and we had a chance to go on stage and receive the certificates amidst a flurry of flashes and a steady applause from the crowd. I really appreciate that they took the trouble of presenting every team with certificates on stage. It made me feel a whole lot less of a loser.

We had a good dinner, and were asked to stay back for the official photo session. We sat on the soft green lawn discussing rarely-told stories about each of us: funny, weird, goofy, romantic and what not: geeks keep no secrets from fellow geeks. My senior, who had made it to ICPC as part of another team, and I discovered we had nurtured a crush on the same fellow competitor after getting there, a good looking mallu girl who sure could code, and were fighting over her. Everybody had something to talk about, and we quickly left our failures behind and were moving on already.

Day 4

Hospitality seems abundant at this college set in a village town. The fourth day saw us driving off on five buses on an excursion to Thenmala, a hill station in south eastern Kerala, one of the more recently discovered and exploited tourist spots, a plethora of awe inspiring landscapes, with a few monkeys thrown in.

The bus ride was fun, though not everyone would agree. I’m the kind that can sit in a cage on wheels peering outside for any amount of time without complaining. Most people were sleeping in the bus, because we had reported at 5:45am and started in another three quarters of an hour. The bus ride was a whole lot more fun once they woke up.

We stopped at the Lookout Point for breakfast: nothing like a breathtaking view of a vast expanse of forests endorsed by a long range of evergreen hills grayed by the slightest cover of mist to help digestion.

We climbed up what are called the Ambanaad Hills, if I remember the name right. The road was treacherous, with gutters, twists and turns making the bus feel like a raging bull in rodeo. The climb was so steep and the roads so narrow at parts that only two of the five buses could make it all the way up, and the other three stopped midway, and had to wait for the two to ferry all of their passengers the rest of the way batch by batch. The hairpins were so sharp that the buses couldn’t take them in one go. I was sitting at the very back, and wasn’t less than a little scared when I seemed to be hovering in mid air, as the buses backed up till their tires were dangerously close to the edge, so that they could make the turn.

The treacherous climb was well worth the boredom and scares as we saw when we came to our destination. We pulled up somewhere close to the top of a hill, and hiked up the rest of the way. We came across a tea plantation interspersed with spices like pepper. Most people were interested in this, although it was something I used to see in my backyard: being a local sure doesn’t help sightseeing. We saw several exotic plants on the way, the most memorable being one with red leaves, which, when seen from a distance, look like flowers. There were several rock faces that begged us to climb them, and several that looked out of the hill, and into the sea of green far down below, and the hills and the trees in the horizon, silhouetted against the dim white of a cloudy sky. I’m cutting this paragraph short for want of words.

We made our way back down to have lunch at a KTDC restaurant. There was a bus waiting for us. A few volunteers were already in it, and the other contestants made their way in. My college mates and I were the last to get there, so we were left with no seats. Seeing this, the staff from the host college started asking them to get down, so that we may take seats. After having leached off their hospitality for the past three days, we felt like rich little bastards throwing their weight around. We tried telling the staff that we were quite willing and able to stand for a while, but they were relentless. We even told the students that we really didn’t want them to vacate for us, and despite our sincerest efforts, they merely smiled politely and left the bus, saying it was no trouble at all. I could only think of what would have happened in a similar situation in a college like mine. The faculty would just stand around talking on their cell phones, order the students to get down once they had finished discussing their family matters, the students would have been quite unwilling to give up their hard earned seats, and at best, would’ve started trickling out sneering at the visitors. I realized I had written an All India examination, and after so much effort landed up in a place that treats virtues as vice, and holds no values dear.

After lunch, we visited the adventure zone, which had a lot of fun stuff to do, such as mountain biking, boating, shooting and river crossing. Shooting was fun, because I got to show up Suren, who was a reputed rifler, having gone to an NCC camp and everything. I made him wish he hadn’t given me advice about the calibration. River crossing was more of a pond crossing. I don’t think the water made any difference. The robotic Kazakh coaching darting across the river (pond) on a flying fox cheered up the ladies.

We returned to college after having snacks from the same KTDC restaurant. The driver we had for our bus was quite a Schumacher in the making. We were scheduled to get back to college by 9:45 pm, but he made it by 8:45 and that after taking some five minutes out to refuel. We just had enough energy left to have dinner, pack up and go to sleep. Suren had left that night itself, and I, the next day morning, leaving Nutty to stay on till the evening.

A Word of Thanks (well, two of them)

I really appreciate the amount of toil our hosts had undergone to put up a great show. Being a Keralite, I’m no stranger to the widely acclaimed Malayalee Hospitality, having been on either end of it myself, but what we saw there was really something else. It felt really nice to walk up to a help desk, and find that the volunteer there actually cares about your predicament, and didn’t think twice before going out of his/her way to tell you what you wanted to know, or get you what you wanted to have. To see that the students were doing what they did of their own accord, as exemplified by the bus drama, and not as a result of threats from the staff was quite inspiring.

Credit must go to my teammates for putting up with a lifeless git like me. I learnt a lot from the two over the last few months when we were preparing, although, apparently, not quite enough. I began to see the pros in Suren’s use of macros to reduce code size and subtle errors in the process. Nutty’s resilience with problems and his command over math are things you wouldn’t fail to notice. I can’t help but feel more than partly at fault for the bad contest. I broke under the pressure I had mounted on myself.

The Epilogue

The four days have left quite a mark. I saw how many people from different parts of the continent are so much better than me at what I have always tried to excel at. I saw how complacent I had become, when there was so much more to do and so much more to be. I saw how different, and how much healthier the environment at what one might consider a lesser college could be. I saw how much of my own self I had forgotten in the last two years and a half since I got shipped off to college.

Now, my goals seem well defined, my path well etched out. I saw the reality that certain people’s ill-advised or ill-meaning flattery was blinding me to, and it turns out it’s time to turn a blind eye to them. It’s time to shake off meaningless responsibilities that I never had to break a sweat to earn, and that I earn nothing from, save for a few half witted critics and around the same number of imbecilic enemies. It’s time I realized my full potential.

This marks the end of an old beginning.

Saturday, May 31, 2008

How to code

Well, I think this post might start off my tech-blogging spree. That’s not to say much about the original spree. Three posts in two years’ time doesn’t quite fit the definition of one.

This one goes out to all of you out there who have just done 12th standard or typical first year B Tech C or C++ and, in my opinion, have a lot of things to unlearn. Some of you may find the content in this post shocking, some even offensive, but hey, I present facts as they are, and I didn’t write the standards documents.

Yes, there are standards documents for C and C++, very detailed guidelines regarding how to write clean, portable C and C++ code. Download them for free from http://www.open-std.org/.

Before starting, I’d also like to make a few disclaimers:

  • I’ve tried to keep the content of this post as technically accurate and unambiguous as I could help it. Wherever appropriate, I’ve cited references, and most of the things I’ve cared to mention here are probably explained in more detail at the references.
  • Being a C++ programmer myself, some of the content in this post might be C++ specific. Though the languages share many things in common, there are many subtle differences. I’ve made efforts to highlight these differences wherever necessary. On the other hand, having used C++ most of my life, when it comes to C, there might actually be differences that I don’t know about. It’s up to the reader to verify the authenticity of such content in this post. (http://www.c-faq.com/ might come in handy.)
  • If you find some errors in this post, please post them as comments. I’ll do my best to verify and post the corrections here as early as possible.

The order in which topics follow is quite random. Most of them are unrelated, and you can probably read the ones that intrigue you the most.

Important terms:

I’m copy-pasting a few definitions with examples from the standards documents here.

Undefined Behavior:

behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

For example, the behavior of your code on integer overflow, or the behavior of constructs like a = a++; are undefined.

Undefined behavior doesn’t mean that your code wouldn’t compile. It simply means that the standards specify no requirements on the behavior of your code. For all you know, your program might start baking cookies.

This is probably a good time to point out that just because your code compiles without errors, it doesn’t mean the code is absolutely right. Going a step further, protests like, “a = a++; seems to be working fine for me,” are meaningless, and are equivalent to saying, “I was playing soccer the other day, and threw the ball into the goal post with my hands, and it worked fine!”. That’s just not the way the game is played.

Try this page, for more information: http://www.eskimo.com/~scs/readings/undef.950311.html

Unspecified Behavior:

use of an unspecified value, or other behavior where this International Standard provides two or more possibilities and imposes no further requirements on which is chosen in any instance.

For example, the order in which arguments are evaluated in a function call.

Implementation Defined Behavior:

unspecified behavior where each implementation documents how the choice is made

An example would be the propagation of the high-order (most significant) bit when a signed integer is shifted right.

Locale-specific Behavior:

behavior that depends on local conventions of nationality, culture, and language that each implementation documents

Example, whether islower() returns true for characters other than a-z is locale-specific.

Further, as far as C or C++ is concerned, the terms byte and char are, for the most part, interchangeable. Consider the following definitions as per the standards:

  • sizeof returns the size of an object, or a type in bytes.
  • A char is a single-byte character, this means that sizeof(char) is 1 by definition.
  • A byte is an addressable unit of data storage large enough to hold any member of the basic character set of the execution environment.

Putting these pieces together tells you that a byte needn’t be 8 bits anymore. In fact, if I made a standards-compliant C compiler that works with Unicode, rather than ASCII, my chars would need 16 bits. But sizeof(char) is 1, and sizeof returns size in bytes. That means, for my implementation, a byte is 16 bits of data, not 8 bits. The number of bits in a byte is specified by the macro CHAR_BIT found in limits.h (climits, in C++).

Good code should try not to rely on the number of bits in a byte being 8. In most cases, you should be able to do without such assumptions. Use the CHAR_BIT macro if absolutely necessary.

Let's begin, then.

Why main shouldn’t be void:

This is definitely going to be new to somebody who hasn’t seen books other than Kanetkar’s or Sumita Arora’s. void main() is wrong!

The explanation given in these books for such usage is something like, “we do not wish to return any values from main, so we mark it as void.” But main() isn’t any other function, now, is it?

As far as the standards go, main must return int, and only int: (this is with reference to a hosted environment: your C or C++ program runs with the help of an operating system)

5.1.2.2.1, C

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

 int main(void) { /* ... */ }

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

 int main(int argc, char *argv[]) { /* ... */ }

or equivalent; or in some other implementation-defined manner.

The standards clearly specify two valid ways to define main, and they both return int. (And or equivalent simply means that int may be substituted by some other name typedefed to int, or that char *argv[] may be replaced by char **argv and so on.) In fact, a program that defines main in a way not equivalent to either of these specified forms invokes Undefined Behavior.

The question is, where does this return value go? Well, the value returned by main goes to the calling system, something that invoked your application. In many cases, this might be the operating system. It may also be some applications written by other programmers like you. The return value of main is a handy way to test whether your program executed correctly, a lot handier than having to look at the error stream of your application, and parsing it to figure out if something went wrong. Generally, a return value of 0 indicates success, and a non-zero value would stand for different error codes.

As an example, let’s say I’m making an installer, and you’ve already made an application to unpack archives. I can simply run your application with necessary arguments, and check the return value to see if your application extracted my archive correctly.

Sizes of structs:

Consider a struct defined as below:

 struct MyStruct {
int a;
char ch;
};

If you’ve learnt that sizeof(MyStruct) would yield 3, it’s wrong. For one thing, the size of an integer is specified to simply be the natural size suggested by the architecture of the execution environment. This means that an integer can be 2 bytes or 4 bytes, or how many ever bytes as the implementation sees fit.

Now, is sizeof(MyStruct) == sizeof(int) + 1?

The answer is still no, thanks to something called structure padding. Compilers are free to pad structures with excess bits (or bytes) for optimization purposes. Generally, structure padding is done in a way as to align the objects with words of the system. On a 32 bit system, for example, this kind of padding would leave structure sizes to be a multiple of four bytes. Hence, the above struct can very well weigh in at 8 bytes.

See the wikipedia page that deals with this: http://en.wikipedia.org/wiki/Data_structure_alignment

http://www.goingware.com/tips/getting-started/alignment.html might prove to be a good read too.

No more conio.h:

There is no such thing as a conio.h as far as standard C or C++ goes. Or a graphics.h. DOS mode graphics are obsolete, and ought to be done away with.

No more clrscr(), either. Though system(“cls”); and system(“clear”); may prove to be alternatives.

But do you really want to clear the screen? On a terminal like Windows’, clearing the screen practically wipes out everything that the user had on his terminal. There is no way to retrieve the information (as far as I know). What if he’d spent the last few decades calculating the first billion gazillion digits of PI? (in which case, he ought to have redirected the output to a file, but, hey, what the heck? This is just an example. Besides, I doubt if a Windows machine could have such uptimes.) Would you wash it all away without even warning the chap? I wouldn’t.

Short circuit evaluation:

The logical and (&&) and or (||) operators operate by what’s known as short circuit evaluation. (The last time I checked, Balagurusamy didn’t know about this.)

What this means is that they guarantee left to right evaluation of operands, plus:

  • The && operator evaluates the expression on the right hand side only if the left hand side evaluated to true.
  • The || operator evaluates the expression on the right hand side only if the left hand side evaluated to false.

Think of it as a kind of optimization. If the left hand side of an && is false, the result is going to be false, so there’s no point in evaluating the right hand side (who knows how long a function call might take, eh?). Same kinda thing goes for ||.

Besides possibly saving some time, there are a few notable consequences to this.

For example, thanks to short circuit evaluation, expressions like:

 b != 0 && a / b < 100
p != NULL && p->value == 50

and so on become inherently safe.

You can also use handy expressions like:

strcmp(str1, str2) || cout << “Strings are equal!” << endl;

(I’d consider this a little difficult to read, especially for people who don’t know what short circuit evaluation is, and avoid this as far as possible.)

As another example, try:

 int i = -1, j = 5;
int k = ++i && ++j;

Does j get incremented? No.

(C++ only) structs can have member functions:

As far as c++ goes, structs and classes are the exact same thing. structs have public visibility by default, while classes have private. Other than this, possibly small, difference, you can do anything with structs that you can do with classes. Add member functions, inherit them, anything!

Why a = a++ is undefined:

This was an example I used earlier in the context of Undefined Behavior. Perhaps I can elaborate a bit more on why this construct invokes Undefined Behavior in this section.

The standards clearly say:

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.

This pretty much gets all different combinations like

 a = a++;
a = a++ * ++a;
A[a] = a++;

and so on out of the way for good.

To understand the statement, however, we need to know about side effects and sequence points.

Side effects are basically changes of the state of the execution environment, like, for example, modifying an object, modifying a file, etc., or calling functions or using operators that involve these kinds of operations. For example, in a simple a++, the increment is a side effect.

Sequence points are points in the execution sequence where all side effects of previous evaluations have taken place, and no side effects of subsequent evaluations will have taken place. The end of a full expression, for example, denotes a sequence point.

In a = a++; consider the two consecutive sequence points, one immediately before and one immediately after the statement. You’re modifying a with an increment, as well as trying to assign a new value to a using the = operator. Two modifications between two consecutive sequence points, undefined behavior.

To be a bit plainer, just know that the exact point of time when the ++ increments a is not specified. It is guaranteed that the increment will occur before the next statement, and that’s about it. This leaves several possible ways in which the expression can be evaluated, all of which are completely valid, as far as the standards are concerned, two of which might be:

  1. Perform the assignment, and then the increment. In this case, the value of a gets incremented by 1.
  2. Store the original value of a in a temporary variable, perform the increment, and then assign the value in the temporary variable back into a. In this case, the value of a remains unchanged after the expression.

This kind of a discussion itself is pointless, but I’m including it here for those of you who need stout examples.

Why fflush shouldn’t be used on stdin:

 int fflush(FILE *stream);

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

This simply rules out any possibility of using fflush on input streams. And for good reason. What does flushing an input stream mean, anyway? Does it make sense? Flushing refers to writing out all the left over contents in a buffer. Why would you ‘write out’ contents in an input stream?

To clear the input stream, use a function similar to the one shown below:

 void clear_stdin() {
char ch;
while((ch = getchar()) != '\n' && ch != EOF);
}

More intelligent use of scanf might save you the hazzle of having to clear the input stream at all. See http://www.cplusplus.com/reference/clibrary/cstdio/scanf.html and pay close attention to the section named 'Whitespace character'.

I can access private variables with pointers!:

Such a statement simply betrays all the misconceptions you have about 'data hiding'.

Firstly, an object is a physical entity that resides on your computer's memory, so yes, a little bit of low level code can tell you what's stored in it. So you're working no magic here.

Secondly, when we say 'data hiding', we simply mean that keeping data members in private sections of your classes will save them from being altered accidentally. Keeping data private gives your class a certain level of confidence about the different states it might find the data in at any point of time, because after all, it's just the class that can meddle with the data right? One needs to understand that such 'data hiding' is simply a kind of contract that you make, which details what are the right ways to work with a class, and what aren't. It's up to the users of the class to follow these guidelines while working with objects of the class.

What are string literals?

A double quoted string lying around in the code is a string literal.

For example, in cout << “ruggedrat” << endl; “ruggedrat” is a string literal.

What are the consequences?

Try

 char *str = “ruggedrat”;

Now, str is a pointer to a literal. This means that any attempts to modify ruggedrat to ruggedbat, like, say, str[6] = 'b'; invokes undefined behavior.

str is a const char * and you'd do well to declare it that way too. To create a mutable string, use one of the following:

 char str[10] = “ruggedrat”;
char str[] = “ruggedrat”;
char str[10]; strcpy(str, “ruggedrat”);

or some equivalent.


I think that should do for now. There are a lot of other issues I could have taken up in this post, but my aim is neither to create a complete C++ reference here, nor to break the longest blog post record. This post is just aimed at directing people to good C and C++ coding practices, and showing where to find more information on them.

I'd conclude by saying that the compiler is just an executable. It's not a foe you're supposed to overcome. In fact, you'd do well at programming once you realize it's quite the other way around. Efforts at cheating a compiler beats the purpose of having one, and better programmers would see them merely as a vulgar display of your ineptitude at using the language.

Throw away outdated books, and delete antique compilers. Get the standards documents, and start writing clean applications.

- A Rugged Rat exhausted from all the typing.


P.S. A few neat FAQs to learn from:

Saturday, April 26, 2008

Encored!

Over the weekend, I was informed that I was to become part of Delta (™, I think, or maybe it was ®) Core, the Central Webteam1 of the college, the elite2 group that takes care of NIT-Trichy’s official website, and all their LAN services, among other things.

“Hey, RR, we decided next year’s core. It'll be you and Bharath," said the head honcho3. "Bhattu will be so surprised!” he added, somewhat shamelessly.

Sure he will. And I’m just a robot. I won’t be surprised. We robots are never surprised. At best, we might throw an exception.

Not extremely sure what to say to what might be construed a cold reception, I just nodded, and let out a squeaky, stifled, ‘yay’, which the head honcho pretended not to hear. Perhaps, I hoped, the casual welcome was designed simply to not throw me off my working spree. Having spent a really long year working on a Content Management System4, during the course of which, PHP and MySQL had threatened to become second nature, it was clear I’d go on a sabbatical at the faintest knock of much anticipated opportunity. A parade and a party to celebrate the occasion, I hoped he feared, might just do the trick.

Having gotten into the Central Webteam in such spectacular fashion, the next question was, what do I do once I’m in there? What’s in store for the next couple of years?

Those astrology websites proved to be of little use to this end. They were more worried about my relationships and finances than I was. Despite the numerous good things they said about me and promised would happen to me, neither have I had a relationship until now, nor have I touched a penny that wasn’t eventually spent on food.

A little digging showed that Delta Core happens to be the secret-keepers of the Octa LAN, for those of you who are Harry Potter fans. They hold the passwords to pretty much all of the servers lying around, and most importantly, the lovely Mac kept in one corner of Sun Lab that gracefully glints in the sunlight coming through the smoked windows, and even plays music.

One thing’s for certain, more coding, lots of decision-making, and several night-outs5 await, and we robots don’t complain. At best, we can throw an exception.

- Rugged Robot

1 Central Webteam: The Central Webteam of NIT-T. More information here: http://www.nitt.edu/home/students/clubsnassocs/computing/delta/webteam/

2 Elite: I like to call it that. Delta Core means a lot of work, and we don’t get paid. I gotta have something to hang on to.

3 Head honcho: Find a more detailed description here: http://parijat-cybertechie.blogspot.com/2008/02/adventure-that-is-life.html (paragraph 6)

4 Content Management System: The Pragyan (™, I think, or maybe it was ®) CMS. Woo hoo! It’s on SourceForge: http://sourceforge.net/projects/pragyan/

5 Night-outs: A sleepless night; generally spent outside one’s hostel, in most cases, at the Octagon6.

6 Octagon: NIT-Trichy’s Computer Center7.

7 Ok, enough, already!