DEV Community 👩‍💻👨‍💻

Cover image for Learn IoT from scratch #5- C/C++ basics for embedded systems
José Thomaz
José Thomaz

Posted on • Updated on

Learn IoT from scratch #5- C/C++ basics for embedded systems

Introduction

This is the #5 post of the IoT series that I am writing, in this article I will talk about primitive data types in C/C++, native libraries, data structures, memory allocation. It is also very important to know what are the main compilers for each of these languages.

To be a good embedded systems engineer you don't need to be THE BEST programmer in these languages, but you need to know their details and how they work behind the scenes. In this post I will not teach you everything about these languages, I will just give you an introduction, and you should seek to delve into these technologies by reading books, attending classes or anything like that.

 

History

I like to know about the history of the technologies that I use at work, at college or in my own studies and researches. I think that histories are very good for us to turn off the zeros and ones mode, and chill a little bit. If you don't want to know the history of C and C++ you can just jump this section of the article.

C

The origin of C is closely tied to the development of the Unix operating system, originally implemented in assembly language, it was released in the early 70s. C was developed to make the Unix OS and its tools development easier, the creator was Dennis Ritchie together with Bell Labs, and with great contributions from Ken Thompson (the creator of Unix).

Dennis Ritchie and Ken Thompson

Initially Dennis started to improve the B language, but these improvements resulted in a completely new language, this language was C, and believe me, the C language was born from a programming language called B 😆. C language was first released in 1972, its preprocessor was introduced in 1973 and the language was first standardized at 1989.

C++

In 1979, Bjarne Stroustrup, a Danish computer scientist, began work on "C with Classes", the predecessor to C++. The motivation for creating a new language originated from Stroustrup's experience in programming for his PhD thesis. Initially it would be just a super-set for the C language, but Stroustrup wasn't having too much progress, so he decided to made it a complete new language.

In 1982, Stroustrup was also working at the legendary "Bell Labs", and he started to develop a successor to C with Classes, which he named "C++" (++ being the increment operator in C) after going through several other names. New features were added, including virtual functions, function name and operator overloading, references, constants, improved type checking.

Bjarne Stroustrup seated at his desk

In 1984, Stroustrup implemented the first C++ native libraries. And in 1985, the first edition of The C++ Programming Language was released, which became the definitive reference for the language, as there was not yet an official standard. The first commercial implementation of C++ was released in October of the same year.

 

Primitive data types

C

int

Basic type, it stores integer numbers and has a size of at least 2 bytes. Integer values can have modifiers such as: signed, unsigned (only values >= 0) and long (integer with a bigger range).

int a = 10; // signed
unsigned int b = 5; // unsigned
long int c = 48492909302020; // long
Enter fullscreen mode Exit fullscreen mode

float

Basic type, it stores floating-point numbers. The float data type is usually referred to as a single-precision floating-point type.

float d = 11.987;
Enter fullscreen mode Exit fullscreen mode

double

Basic type, it also stores floating-point numbers. The float data type is usually referred to as a double-precision floating-point type. So a double variable is more precise than a float one, and it could be more appropriate when dealing with algebra, complex math, etc.

double e = 11.987;
Enter fullscreen mode Exit fullscreen mode

char

Smallest and simplest data type in C, the char type stores a single character and has a size of 1 byte;

char yes = 'y';
Enter fullscreen mode Exit fullscreen mode

string (char * or char[])

In C programming, does not exist the string data type, so a string is a sequence of characters terminated with a null character \0. So you can use char arrays or char pointers, with char arrays you can get the length of the string easier, but you cannot pass it as a parameter to a function, neither reassign and/or modify the string value without the string.h native library.

There are many ways to declare a string in C, so let's see some code examples:

char a[] = "abcd";
char b[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char d[5] = {'a', 'b', 'c', 'd', '\0'};
char * e = "abcd"; // string declaration using pointers
char f[100]; // the string was declared, but wasn't initialized
Enter fullscreen mode Exit fullscreen mode

bool - ??? 🤔

The C language doesn't have "bool" as a primitive data type, so in C when we want to deal with boolean values, expressions
and statements, we have to use integer values to evaluate boolean values. So let's suppose that we have an statement, if it returns a zero, the statement is false, otherwise, if it returns a one, the statement is true.

Now to really understand all this boolean stuff, let's see an example of how would this code be in C:

int f = 10;
int g = 20;
printf("%d \n", f > g); // 0 -> False
printf("%d \n", f < g); // 1 -> True
Enter fullscreen mode Exit fullscreen mode

If you are familiar with higher level programming languages, that have the "bool type", you may have difficulty using 0 and 1 for boolean operations/values. So you can use the stdbool.h native library, it is available since C99, and is the best way to use bool in C.

#include <stdio.h>
#include <stdbool.h>

int main(void) {
    bool keep_going = true;  // Could also be `bool keep_going = 1;`
    while(keep_going) {
        printf("This will run as long as keep_going is true.\n");
        keep_going = false;    // Could also be `keep_going = 0;`
    }
    printf("Stopping!\n");
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

void

Void is considered a data type (for organizational purposes), but it is basically a keyword to use as a placeholder where you would put a data type, to represent "no data". Accordingly to some standards void is an incomplete data type, because you cannot declare a variable with type void, but you can use void for declaring pointers (void * or void **) and functions.

void myFunc(int a, int b, int c) {
    c = a + b;
}
Enter fullscreen mode Exit fullscreen mode

C++

string

The C++ language also doesn't have the string data type by default, as a primitive data type. But you can include the string native library, this library contains the string data type, and some functions to manipulate strings, the string library of C++ is very similar to the string.h library of C.

#include <iostream>
#include <string>

using namespace std;

int main (void) {
    string str1 = "Hello";
    string str2 = "World";
    string str3;
    int  len ;

    // copy str1 into str3
    str3 = str1;
    cout << "str3 : " << str3 << endl;

    // concatenates str1 and str2
    str3 = str1 + str2;
    cout << "str1 + str2 : " << str3 << endl;

   return 0;
}
Enter fullscreen mode Exit fullscreen mode

bool

In C++, the data type bool has been introduced to hold a boolean value, true or false.The values true or false have been added as keywords in the C++ language. Unlike the C language, C++ has a native bool type, not as a constant, a macro, or an enum.

#include<iostream>
using namespace std;
int main (void) {
    int x1 = 10, x2 = 20, m = 2;
    bool b1, b2;
    b1 = x1 == x2; // false
    b2 = x1 < x2; // true

    cout << "b1 is = " << b1 << "\n";
    cout << "b2 is = " << b2 << "\n";
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

 

Structs (C/C++) X Classes (C++)

Structs and classes are similar, with both of you can create models, entities, and build a structure type with multiple fields, and these fields can have equal data types, but also different. The c language only supports structs, whereas the C++ language supports both structs and classes.

The only difference between a struct and class in C++ is the default accessibility of member variables and methods. In a struct they are always public, but when do you use classes, you can define variables and methods as public, protected or private.

Also, classes were designed to follow to Object-Oriented paradigm, so using them it is too much easier to implement concepts like polymorphism, inheritance, abstractions and dependency injection. It is possible to implement these concepts with structs, but it is much harder and you might have to write more lines of code.

struct Foo {
   int x;
};

class Bar {
    public:
        int x;
};
Enter fullscreen mode Exit fullscreen mode

 

Main compilers for C

The C programming language has at least 50 known complete compilers, but this list contains the 3 more popular compilers.

  1. GCC
  2. CLang
  3. TurboC

Main compilers for C++

The C++ programming language has more than 20 known complete compilers, but this list contains the 3 more popular compilers.

  1. GCC (g++)
  2. CLang (clang++)
  3. Intel C++ Compiler (icc)

 

Book references

If you don't have previous experience using C/C++, I recommend that you go deeper and look for content from other sources, and books are always great sources of knowledge.

  1. The C Programming Language - "Known as the bible of C, this classic bestseller introduces the C programming language and illustrates algorithms, data structures, and programming techniques. This book has 2 authors, one of them is Dennis Ritchie, the creator of the C programming language"...nothing better than learn from who has created it, right?

  2. Head First C - "Head First C provides a complete learning experience for C and structured imperative programming. With a unique method that goes beyond syntax and how-to manuals, this guide not only teaches you the language, it helps you understand how to be a great programmer. You'll learn key areas such as language basics, pointers and pointer arithmetic, and dynamic memory management."

  3. Expert C Programming: Deep C Secrets - "This book is for the knowledgeable C programmer, this is a second book that gives the C programmers advanced tips and tricks. This book will help the C programmer reach new heights as a professional. Organized to make it easy for the reader to scan to sections that are relevant to their immediate needs."

  4. The C++ Programming Language - "The C++ Programming Language, Fourth Edition, delivers meticulous, richly explained, and integrated coverage of the entire language, its facilities, abstraction mechanisms and standard libraries. Throughout, Stroustrup presents concise examples, which have been carefully crafted to clarify both usage and program design."

  5. C++: The Ultimate Beginners Guide to Learn C++ Programming - "How to set up a C++ development environment- The principles of programming that will get you started- The different operations in C++: binary, arithmetic, relational, etc.- Power of C++: operations, switches, loops and decision making - Getting started: syntax, data types, and variables- How to create custom functions in C++- The best practices for coding- A useful glossary at the end- And more..."

 

Course references

If you don't like to read books, or if you have difficulties to understand them, you can take courses, there are many free options of courses available. I will recommend free and paid courses that I think that are very good.

  1. CS50 Week 1 - In week 1 (2nd week) of CS50, a basic C course is taught, introducing the language.

  2. C Programming Tutorial for beginners: freeCodeCamp - This course will give you a full introduction into all of the core concepts in the C programming language in 4 hours.

  3. C++ Programming Tutorial for beginners: freeCodeCamp - This course will give you a full introduction into all of the core concepts in the C++ programming language in 4 hours.

  4. C++ FULL COURSE For Beginners (Learn C++ in 10 hours): Code Beauty - This is a full C++ programming course. It consists of many lectures whose goal is to take you from beginner to advanced programming level.

 

Conclusion

We have reached the end of our article, this was a very long post. Know C and C++ is essential to be a good IoT developer, because you will be able to work with high-performance systems, embedded systems and also programming of sensors.

Obviously this post doesn't contain everything you need to know, because it's a very dense subject, but I tried to summarize as best I could, to make the information clear and allow you to go deeper into the subject.

Top comments (4)

Collapse
funbeedev profile image
Fum

Great article. Keep going with the series, I'm enjoying it so far!

Collapse
josethz00 profile image
José Thomaz Author

I'm glad that you are enjoying it and still reading, I have paused the series because I'm on exam period at college, but this weekend I will resume the posts!!

Collapse
duartelucas profile image
Duarte Lucas

Loving it. Will be forced to dive into C, so this series is great. Gives some purpose to it all. xD

Collapse
josethz00 profile image
José Thomaz Author

I'm glad you liked it, I paused the series because I'm on exam period at college, but this weekend I will resume the posts!!

🌚 Life is too short to browse without dark mode