Thursday, February 2, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home C++

5 C++ Tricks for C Programmers

learningcode_x1mckf by learningcode_x1mckf
September 15, 2022
in C++
0
5 C++ Tricks for C Programmers
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


You might also like

C can be memory-safe – Security Boulevard

C++ Lambda Expressions Explained | Built In

C++ creator Bjarne Stroustrup defends its safety

Over the previous a number of years, C++ has turn into a extra in style language to make use of in embedded methods than C. Don’t get me fallacious, C will proceed to be a dominate language for years to come back, however C++ gives builders fashionable instruments to leverage when designing extra reusable, scalable, and transportable code. Groups aren’t simply abandoning C, however as an alternative, when beginning new product growth are as an alternative adopting C++. The language has been evolving with the instances and gives many enhancements over C. On this submit, let’s look at 5 easy C++ methods that C programmers will instantly recognize.

Trick #1 – Conditional Compilation Utilizing Constexpr

The bane of many embedded code bases written in C is the big numbers of #if / #elif / #else preprocessor directives. The preprocessor directives are sometimes used to conditionally compile code out and in of the picture. For instance, if now we have three totally different variations of {hardware}, we’ll usually create a macro that’s used after which checked based mostly on the construct configuration to find out pin assignments and so forth. The issue with conditional compilations utilizing the preprocessor is that the code will get messy and typically fairly troublesome to comply with.

Associated: 5 Tips for Choosing an Embedded Programming Language

Beginning in C++ 17, the language launched the flexibility for builders to conditionally compile code utilizing constexpr. Builders can leverage this compiler function to optimize code based mostly on templates and even to take away preprocessor directives which might be utilizing #ifdef blocks. For instance, if we had a code base that had three totally different {hardware} configurations, we’d discover that our code to initialize GPIO appears one thing like this:

void Gpio_Init()

Associated: Utilizing CI/CD Processes for Embedded Systems

#ifdef __HARDWARE_REV1__

            // Initialize pin set #1

#elif __HARDWARE_REV2__

            // Initialize pin set #2

#elif __HARDWARE_REV_3__

            // Initilialize pin set #3

#endif  

 

The code above is configurable, but it surely’s fairly nasty to have a look at. Sure, a contemporary IDE will shade a number of the choices, but it surely’s simply not a really elegant answer and results in some messy code. In C++, we are able to leverage the constexpr compile time optimization and write code like the next:

constexpr Hardware_t HardwareRev = {Hardware}::Rev1

void Gpio_Init()

    if constexpr (HardwareRev == {Hardware}::Rev1)

   

        // Initialize pin set #1

   

    else if constexpr (HardwareRev == {Hardware}::Rev2)

   

        // Initialize pin set #2

   

    else if constexpr(HardwareRev == {Hardware}::Rev3)

   

        // Initialize pin set #3

   

Once we compile the above code for Rev2, solely the code for “Initialize pin set #2” makes it into our executable. If we compile for Rev1, solely the code for “Initialize pin set #1” makes it into the executable, and so forth.

Trick #2 – Ranged for Loops

A elementary move management mechanism in C and C++ is the for loop. The C for loop has been caught at the hours of darkness ages by not having a simplified range-based possibility. For instance, languages like Python enable a programmer to iterate over a variety utilizing syntax like:

for x in vary (1, 5)

    print(x)

In C, we have to write (relying on the C commonplace used after all):

for(int x = 1; x <= 5; x++)

    printf(“%d rn”, x);

Beginning in C++ 11, an extra model of the for loop was added that makes working with ranged values simpler. For instance, if one needed to write down the above code examples in C++, we might now write it as:

int MyNums[] = 1, 2, 3, 4, 5;

for(int i : MyNums)

    std::cout << I << std::endl;

At first, to a C developer this will likely appear awkward; Nevertheless, given how usually we need to work over a variety in an enum or object, the syntax is cleaner and simpler to learn.

Trick #3 – Use Auto

For C builders, auto is a language key phrase that was deprecated a very long time in the past. Builders used to make use of auto to specify a variable that was restricted to the present scope. Auto is a storage class specifier like static, solely it specifies that the storage is native and the variable must be routinely destroyed as soon as our of scope, not like static which permits the variable to persist.

In C++, auto could be a very helpful key phrase that tells the compiler to routinely assign the datatype for the developer. For instance, in Trick #2, we had the next for loop code:

int MyNums[] = 1, 2, 3, 4, 5;

for(int i : MyNums)

    std::cout << I << std::endl;

MyNums is already outlined as an int, so I can let the compiler resolve on the kind that must be used for i as follows:

for(auto i : MyNums)

    std::cout << I << std::endl;

At first, this will likely seem sloppy. Because the developer, shouldn’t I management what my variable varieties are? The reply is sure, however we must always enable the compiler to handle varieties the place it might save us time or the place we don’t care to manually specify. Will we care if i for instance is uint8_t, uint16_t, uint32_t and so forth? Most likely not. We simply need one thing that may iterate over the vary of 1 to 5 and the compiler is greater than able to deciding. Auto may also assist once we change a knowledge sort. We will change it in a single place with out having to fret about altering something downstream that makes use of or interacts with it.  

Trick #4 – The Spaceship Operator

It will possibly typically be annoying when it’s essential to write a conditional assertion that checks whether or not a worth is lower than, better than, or equal to a different worth. Only recently, C++20 add a three-way comparability operator that may simplify readability and the code. This operator <=>, is usually known as the “spaceship” operator as a result of it appears like a spaceship.

Utilizing the spaceship operator is easy. For instance, if now we have two variables and we would like a three-way comparability, we’d write code like the next:

int Var1 = Value1;

int Var2 = Value2;

auto Consequence = Var1 <=> Var2;

If Var1 < Var2, then Consequence will lower than 0. If Var1 > Var2, Consequence can be better than 0. If Var 1 is the same as Var2, then Consequence can be 0.

Trick #5 – Getting the Measurement of a String

Strings in C are nothing greater than a char array with ‘’ because the final array entry. Many bugs have resulted in functions from how C offers with strings. It’s not unusual to neglect the string terminator in a string, incorrectly dimension the array, or use string features that may end up in buffer overruns, and so forth.

In C++, strings may be managed far more safely. I’m not going to enter all of the cool particulars on this submit, that’s as much as the reader, however I do need to simply level out how easy issues may be in C++. For instance, if a developer must get the size of a string, they’ll merely use the size() technique related to the string. A easy code instance is perhaps the place we enable the consumer to enter a string after which confirm its size prior to make use of:

string Enter;

getline(cin, Enter);

 

if(Enter.size() < 50)

    std::out << “Processing String …” << std::endl;

else

    std::out << “String to lengthy! Attempt once more” << std::endl;

It’s a easy instance, however I extremely encourage the reader to analyze the string libraries which might be supplied in C++. You’ll be shocked how secure, and straightforward it’s to make use of strings!

Conclusions

C++ is gaining traction in lots of embedded functions, particularly ones which might be developed from the bottom up and don’t depend on massive quantities of legacy code. At first look, C++ could appear intimidating to C programmers; Nevertheless, C programmers will discover that C++ is a pure extension of C right into a extra fashionable programming language. Design patterns and methods that will be almost inconceivable in C are simple in C++. On this submit, we’ve explored just a few easy C++ methods that I believe will curiosity C builders. We’ve barely begun to scratch the floor, however if you’re a C programmer, I believe you’ll discover that C++ has loads to supply to embedded functions.

Jacob Beningo is an embedded software program guide who works with shoppers in additional than a dozen international locations to dramatically rework their companies by bettering product high quality, value, and time to market. He has printed too many blogs to depend embedded software program structure, processes, and growth methods, is a sought-after speaker and technical coach, and holds three levels, together with a Grasp of Engineering from the College of Michigan. You possibly can contact Jacob at [email protected] and sign-up for his month-to-month Embedded Bytes Newsletter.

 

 

 



Source link

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

C can be memory-safe – Security Boulevard

by learningcode_x1mckf
February 1, 2023
0
C can be memory-safe – Security Boulevard

The concept of memory-safe languages is within the information currently. C/C++ is known for being the world’s system language (that runs most issues) but in addition notorious for being...

Read more

C++ Lambda Expressions Explained | Built In

by learningcode_x1mckf
February 1, 2023
0
C++ Lambda Expressions Explained | Built In

One of many new options launched in trendy C++ ranging from C++ 11 is the lambda expression.It's a handy solution to outline an nameless operate object or functor....

Read more

C++ creator Bjarne Stroustrup defends its safety

by learningcode_x1mckf
January 31, 2023
0
C++ creator Bjarne Stroustrup defends its safety

The creator of C++, Bjarne Stroustrup, is defending the venerable programming language after the US Nationwide Safety Company (NSA) just lately really helpful towards utilizing it. NSA advises...

Read more

Solid Sands and Rapita target hard to do C++ code analysis … – eeNews Europe

by learningcode_x1mckf
January 30, 2023
0
Solid Sands and Rapita target hard to do C++ code analysis … – eeNews Europe

Solid Sands and Rapita target hard to do C++ code analysis ...  eeNews Europe Source link

Read more

Bjarne Stroustrup Defends C++ As Safe

by learningcode_x1mckf
January 29, 2023
0

It is not stunning to search out the creator of a language defending the language they created and so it's with the newest paper from Bjarne Stroustrup. Is...

Read more
Next Post
Beginner’s guide to the async/await concurrency API in Vapor & Fluent

Beginner's guide to the async/await concurrency API in Vapor & Fluent

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

Oracle’s Java 19 delivers language improvements – Back End News

Oracle’s Java 19 delivers language improvements – Back End News

October 10, 2022
Time limit for notify – JavaScript – SitePoint Forums

Html form tag that blocks a click counter button – JavaScript – SitePoint Forums

November 21, 2022
Azul detects Java vulnerabilities in production apps

Azul detects Java vulnerabilities in production apps

November 6, 2022

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • Java :Full Stack Developer – Western Cape saon_careerjunctionza_state
  • Pay What You Want for this Learn to Code JavaScript Certification Bundle
  • UPB Java Jam brings coffeehouse vibes to Taylor Down Under | Culture

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?