Day 67: Character Array Basics in C

Got down some decent notes on char values and character arrays (a.k.a. strings) in C. I’m trying to be patient and trust the process but man this is taking it’s time. The only positive is that I am getting more comfortable with the language which is something that I always wanted. Rome wasn’t built in a day so I guess a dope software developer can’t be built in a month or year??? (I’m not the best poet here… clearly – LOL)

TLDR;

Okay, so here are the highlights of what I did:

  • Continued to work on the “Technical Questions” section of the book “Cracking the Coding Interview” by Gayle Laakmann McDowell. Within that, I continued my work on Tree data structures. Started trying to replicate the example pretty print functions provided in the article I am reading through. I had to pause working on my Horizontal Pretty Print project to better understand string/character manipulation in the C programming language. It is a bit of a detour but I imagine it will pay itself off in the long run. Continued reading the C programming book called “The C Programming Language” by Brian W. Kernighan and Dennis M. Ritchie. I took notes on character arrays (a.k.a strings) in C. These notes are from chapter 2 in the book where data types are broken down. I also got to review the null/zero character (\0). I have a long way to go but I put a decent amount of effort today and that’s all I can ask out of myself. It’s about the process not the outcomes… At least in my opinion.
  • I continued reading through chapter 6 of the book “Eloquent JavaScript” by Marjin Haverbeke. I am starting to read the book to help cover some insecurities I have about my knowledge of the language. I learned JavaScript on the fly through projects and YouTube videos. There are some core questions about the language that I don’t think I can answer, so hopefully this will help. I was reviewing my notes on class notation today. In Chapter 6 the topic is covered following the introduction to prototypes and classes. I have to criticize the book for their final example on the topic. It related to anonymous class expressions but used a complicated example where an anonymous class expression was immediately used to construct an object all in one line. I had no idea what was happening at first since it was a layered example. I did some digging and figured it out and added some buffer to my notes so that there was a reasonable progression LOL.

C Notes

char and char[] (strings)

Technically a string is an array of characters (char values). The internal representation of a string has a null character \0 at the end, so the physical storage required is one more that the number of characters written between the quotes. Therefore, there is no limit to how long a string can be, but programs must scan a string completely to determine it’s length. The standard library function strlen(s) returns the length of its character string argument (char s[]), excluding the terminal \0strlen and other functions are declared in the standard header <string.h>

// strlen: return length of char s[]

int strlen(char s[]){
  int i = 0;
  while(s[i] != '\0')
    ++i;

  return i;
}

Be careful to distinguish between a character constant and a string that contains only one character e.g. "x" = character string while 'x' = a single character.


JavaScript Notes

Class Notation

So JavaScript classes are constructor functions with a prototype property that is set for all objects built. That is how they work, and until 2015, that was how you had to write them. These days, we have a less awkward notation.

class Rabbit {
  constructor(type){
    this.type = type;
  }

  speak(line){
    console.log(`The ${this.type} rabbit says ${line}`);
  }
}

let killerRabbit = new Rabbit("killer");
let blackRabbit = new Rabbit("black");

The class keyword starts a class declaration, which allows us to define a constructor and a set of methods all in a single place. Any number of methods may be written inside the declaration’s braces. The one named constructor is treated specially. It provides the actual constructor function, which will be bound to the name Rabbit. The others are packaged into that constructor’s prototype. Thus, the earlier class declaration is equivalent to the constructor definition from the previous section. It just looks nicer.

Class declarations currently allow ONLY methods (properties that hold functions) to be added to the prototype. This can be somewhat inconvenient when you want to save a non-function value in there. The next version of the language will probably improve this. For now, you can create such properties by directly manipulating the prototype after you’ve defined the class.

Like functionclass can be used both in statements and in expressions. When used as an expression, it doesn’t define a binding but just produces the constructor as a value. You are allowed to omit the class name in a class expression.

// Syntax for class expressions
const MyClass = class [className] [extends otherClassName] {
  // class body
}

//Example Super Simple Demo of a class expression
'use strict';        // Meaning and usage needs to be addressed 
                     //(perhaps later on in studies)

let Foo = class {};  // constructor property is optional
Foo = class {};      // Re-declaration is allowed

typeof Foo;             // returns "function"
typeof class {};        // returns "function"

Foo instanceof Object;   // true
Foo instanceof Function; // true
class Foo {}             // Throws SyntaxError (class declarations do not allow re-declaration)
// Another simple class expression
// This is just a simple anonymous class expression 
// which you can refer to using the variable Foo.

const Foo = class {
  constructor() {}
  bar() {
    return 'Hello World!';
  }
};

const instance = new Foo();
instance.bar();  // "Hello World!"
Foo.name;        // "Foo"
// Named class expressions

const Foo = class NamedFoo {
  constructor() {}
  whoIsThere() {
    return NamedFoo.name;
  }
}
const bar = new Foo();
bar.whoIsThere();  // "NamedFoo"
NamedFoo.name;     // ReferenceError: NamedFoo is not defined
Foo.name;          // "NamedFoo"
let object = new class { getWord() { return "hello"; } };
console.log(object.getWord());
// → hello

The example above can be a bit confusing but here is the breakdown. In the first line an anonymous class expression is used to immediately construct an instance of that anonymous class. We therefore end up with the instance being bound to the object variable with a prototype derived from the anonymous class expression. The anonymous class expression is not accessible since it was not bound to anything (at least I think).

NOTE: Also apparently all functions have a default READ-ONLY name property that we can access. Since the JavaScript class syntax is really just a neat constructor function under the hood, it also has access to the name property. Apparently this property may come from the Object prototype and not the Function prototype since Object.name works as well??? Object instances do not have access to this property by default though. I wonder why. I tried and it just came up as undefined. Maybe I did something wrong. I have never used this property before so it surprised me. Maybe it’s a class property that gets removed with instances or gets overridden or something. – Article on the topic

NOTE: This note is being written in 2022/01/20 and it seems that the newer version of JavaScript released since writing this book allow for JavaScript prototypes to hold properties as well as methods. Caution should still be taken because this may not work on all browsers/node versions. It could be a relatively new feature. Here is an example where we can clearly see that the name property exists in the prototype and not the object constructed using the prototype. (I could be wrong but it seems to make sense). This has also been mentioned above in the class section.

let finalObj = Object.create({
  name: "Jamal",
  hello(){
    console.log(`Hello ${this.name}`)
  }
});

finalObj.hello();
// → Hello Jamal

console.log(finalObj.name);
// → 'Jamal'

console.log(finalObj.__proto__);
// → { name: 'Jamal', hello: [Function: hello] }

console.log(finalObj.hasOwnProperty('name'));
// → false

console.log(Object.hasOwnProperty(finalObj, 'name'));
// → false

References


Conclusion

That’s all for today. This is my sixth round of the “#100daysofcode” challenge. I will be continuing my work from round five into round six. I am currently working through the book “Cracking the Coding Interview” by Gayle Laakmann McDowell. My goal is to become more familiar with algorithms and data structures. This goal was derived from my goal to better understand operating systems and key programs that I use in the terminal regularly e.g. Git. This goal was in term derived from my desire to better understand the fundamental tools used for coding outside of popular GUIs. This in turn was derived from my desire to be a better back-end developer.

I have no idea if my path is correct but I am walking down this road anyways. Worst case scenario I learn a whole bunch of stuff that will help me out on my own personal projects.