Showing posts with label iso. Show all posts
Showing posts with label iso. Show all posts

Monday, January 2, 2023

Modern C++ features

Modern C++

In this article, I will provide a tutorial on features in modern C++ using very simple examples. The examples will be kept short for beginners to quickly grasp the features.

The complete list of features can be found in the following links: C++11, C++14, C++17, C++20. Please refer to these links for more information.

1 C++11

1.1 nullptr

Considering function overloading:

void fun(int);
void fun(char *);

Traditionally, NULL is often defined as 0. The issue arises with which function will foo(NULL) call?

Thus, C++11 introduces a new kerword, nullptr, as a distinghished null pointer consant.

#include <iostream>

void fun(char *p) {
        std::cout << "hi pointer" << std::endl;

}

void fun(int i) {
        std::cout << "hi integer" << std::endl;

}

int main()
{
        fun(0);       // Calls func(int)
        fun(nullptr); // Calls func(char*)
        //fun(NULL);  // This generates an error
        return 0;

}

1.2 Strongly typed enumeration

Enumerations in C++03 are effectively integers and do not have their own scope. It is possible to compare two enum values of different enumeration types.

#include <iostream>

int main()
{
        enum Animal {Cat, Dog, Elephant};
        enum Fish {Clam, Dolphin, Eel};

        Animal a = Dog;
        Fish f = Dolphin;

        if (a == f)
                std::cout << "Dog == Dolphin" << std::endl;
        else
                std::cout << "Dog != Dolphin" << std::endl;
        return 0;
}

Sunday, December 18, 2022

C11 (C standard revision) features

C11 revision

1 Overview

C11 is the informal name for ISO/IEC 9899:2011, the current standard for the C language that was ratified by ISO in December 2011.

It standardizes many features for safer programming, such as removal of gets() function.

Additionally, C11 adds concurrency support, type-generic expressions, alignment-related facilities, static assertion, unicode support, floating-point characteristic macros, no-return functions, anonymous structures and unions, and various bound-checking and reentrancy functions.

The following examples demonstrating C11 features can be compiled with options such as

clang -std=c11 ex.c

2 Multiple threading

C11 standardized multi-threading support.

It introduces new headers threads.h and stdatomic.h, supporting multiple threads of execution:

  • threads creation and management
  • mutexes
  • conditional variables
  • atomic objects
  • thread specific storage