In the history of modern C++, the C++14 standard brings us some very useful features. C++14 comes with the digit seperators feature. In C++14 and above, we can use the digit separator to separate integer numbers. In this post, we explain, how to use digit separators in examples, How can I use use digit separators in modern C++? In C++14, there is a new Digit Separators feature. The digit separator is a single-quote character ‘ that can be used within a numeric literal for aesthetic readability. When you use digit separators, it does not affect the numeric value, but it is very useful when you are using bigger or longer digital numbers. It can be used with int, long int, long long int, float, double, auto, etc. Here is a simple example to digit separators. long long int LL = 123‘456’789; Is there a full example about to use digit separators in modern C++ Here is a full example about to use digit separators in modern C++. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #include #include int main() { int x = 1‘024; unsigned int m = 128′000‘000; long double pi = 3.141′592‘653’589; long long int LL = 123‘456’789; std::cout
A programming language consists of a lot of expressions in our source code. One of elements of expressions in C++ are literals. A more specific type of literal is Integer Literals. Integer literals are primary expressions that allow values of integer types (i.e., decimal, octal, hexadecimal) to be used in expressions directly. They are further improved by the boolean literals (binary digits) in C++14. In this post, we will explain and list the types of integer literals available to us in modern C++. What is integer literal in modern C++? Integer Literals in C++ are primary expressions that are used to indicate the base or the type of an integer value. They allow values of integer types to be used in expressions directly. They are further improved by the addition of boolean literals in C++ 14. We can categorize integer literals into two groups: Prefixes and Suffixes. What is the prefix integer literal in modern C++? Prefix Integer Literals are used to indicate the numeric base of the literal. For example, the prefix 0x indicates a hexadecimal base (i.e. value 0x10 indicates the value of 16). Here are the prefixes for integer literals (integer-prefix). Prefix Literal Base Example -no prefix- Decimal Literals Base 10 1024 0 (zero) Octa Literals Base 8 048 0x or 0X Hex Literals Base 16 0xFF 0b or 0B Binary Literals Base 2 0b01010111 Here are simple examples to prefix integer literals: int d = 1024; // decimal int o = 076; // octal int x = 0xFF22CC; // hexadecimal int b = 0b10101111; // binary (C++14) What is the suffix integer literal in modern C++? Suffix Integer Literals are used to indicate the type. For example, the suffix LL indicates the value is for the long long integer (i.e. value 98765432109876LL indicates it is a long long integer). When we use suffix, that means this type of the integer literal is the first type in which the value can fit, and there are other decimal types from the list of types that depends on which numeric base and suffix. Here are the suffixes for integer literals (integer-suffix), Suffix Decimal Type Other Decimal Types -no suffix- intlong intlong long int intunsigned intlong intunsigned long intlong long intunsigned long long int l or L long intunsigned long intlong long int long intunsigned long intlong long intunsigned long long int ll or LL long long int long long intunsigned long long int z or Z (C++23) the signed version of std::size_t the signed version of std::size_t std::size_t u or U unsigned intunsigned long intunsigned long long int unsigned intunsigned long intunsigned long long int ul or UL unsigned long intunsigned long long int unsigned long intunsigned long long int ull or ULL unsigned long long int unsigned long long int uz or UZ (C++23) std::size_t std::size_t Here are simple examples of how to suffix integer literals in C++. int i1 = 2048; long i2 = 2048L; // or l long long i3 = 2048LL; // or ll unsigned int u1 = 2048u; // or U unsigned long int u2 = 2048ul; // or UL unsigned long long int u3 = 2048ull; // or ULL The C++23 feature can be tested with this __cpp_size_t_suffix if definition as we show below. #if __cpp_size_t_suffix >= 202011L // (C++23 feature) auto size1 = 0z; // or Z auto size2 = 40uz; // or UZ static_assert( std::is_same_v ); static_assert( std::is_same_v ); #endif Is there a full example about integer literals in modern C++? Here is a full example of how to use integer literals that uses prefixes and suffixes in modern C++. 1 2 3 4 5 6 7 8 9 10 11 […]
Modern C++ has a lot of useful functions coming from C. One of them was the gets() function that we use to get string inputs and that we were able to use in C++11 or earlier. In C++14, the gets function was removed, while fgets or other input functions remain there. If you have older C++ code that uses the gets() functions your C++14 version compiler will not compile it. Why was the gets function removed? In this post, we explain what the gets function is, why the std::gets function was removed by the C++14 standards, and how can we use similar functions or alternatives to the gets() function. What was the gets() function considered dangerous in C++? In C++11 and before, we were able to gets function. The std::gets function was first defined in the C language and was available in C++11 and earlier. The gets function reads inputs into a given char string. When a char string has a newline character, it is considered the end of input, and an end-of-file condition occurs. The return value is captured on success, or a null pointer on failure. The syntax below is deprecated in C++11 and removed in C++14. char* gets( char* str ); Here is an example of a dangerous gets function, #include #include int main() { char str[8]; gets(str); printf(str: %s“, str); return 0; } Why was the std::gets function removed In C++14? According to C++14 document N4140 (Page 1237), the “use of gets is considered dangerous“, because the std::gets function does not check the bounds of a char array. This makes gets extremely vulnerable to buffer-overflow attacks. In other words, the std::gets function cannot be used safely. The std::gets() function was deprecated in C++11 and removed completely in C++14. If you REALLY need to use it in your apps, then there are some alternatives – for example you can use std::fgets(). If we use gets(), it is impossible to tell without knowing the data in advance how many characters will be read, and because std:: gets() will continue to store characters past the end of the buffer, it is extremely ‘dangerous’ to use. Here is the definition from C++14 (Document Number: N4140, Page 1237). C.3.4 Clause 27: input/output library Change: gets is not defined. Rationale: Use of gets is considered dangerous. Effect on original feature: Valid C++ 2011 code that uses the gets function may fail to compile in this International Standard. They added a note to [c.files] saying that the C function gets() is not part of C++ and they removed gets from tables 134 and 153. We should note that there are some compilers that still support the gets() function. The gets function may be only used if the program runs in an environment that restricts inputs from stdin. Are there any alternatives to the std::gets function in modern C++? First of all, never use std::gets() function, use std::fgets() instead or other input methods of modern C++. There is no way to check the size of input before we store data to that variable. If you have older C++ code that uses the gets function and you want to modernize it, you can use std::fgets() as shown below. 1 2 3 4 5 […]
C++ is very strong in every aspect of modern programming and evolves and refines itself even further with the release of each new C++ standard. While there are many new additions there are some features that are found not useful or dangerous in programming, thus the community offers its deprecation in the next standard and then it is generally removed in the following standard. C++14 came with a new deprecated attribute feature to allow marking an entity as deprecated – potentially obsolete and best avoided. In this post, we will explain what deprecated means and how can we use the [[deprecated]] and __declspec(deprecated) attributes in modern C++. What does deprecated mean in C++? Deprecation is the process of taking an older code part (a method, function, or property) and marking it as no longer being useful within the current version of the programming codebase (generally it is a standard, i.e. C++11, C++14) . It also flags that the deprecated feature will probably be removed in the next version of C++. Often this is because a feature or function has been found to be ‘dangerous’ or has been superseded or obsoleted by newer code. The deprecated attribute does not mean it is immediately removed from that C++ version (a standard or a library) because doing so may cause regression errors. Generally, a deprecated feature is going to be removed in the next version or standard. For example, the gets() function was found to have potentially dangerous (undesirable) behavior and it was deprecated in the C++11 standard and removed in the C++14 standard. Briefly, deprecated means, that part of code is considered outdated and not recommended to use, and that the keyword, feature, or function will probably be removed in a subsequent C++ standard. How can we use the deprecated attribute in C++? C++14, came with a new deprecated attribute feature to allow marking an entity deprecated, There are two options to declare something as deprecated. We can use [[deprecated]] and __declspec(deprecated) attributes. The deprecated attribute is very useful to mark your older functions that probably will be removed. When you are working on a code base which you share with other developers it is useful for them to know that a section of code they are viewing is potentially outdated or will be removed – and the deprecated attribute is the best way to do that. While this is necessary for compiler developers (i.e. C++ Builder, GCC, Visual C++), it is also very desirable for library developers. If you find any code that will be removed in the next version, first, you can release a version that has the affected code part marked as deprecated. Then in the next release, you can remove it from your library. This is the modern way of professional programming. The [[deprecated]] attribute allows marking the part of the code entity deprecated, which means it is still available to use but gives a warning from the compiler that the use of the code section is deprecated, it is discouraged and may allow ‘dangerous’ errors on runtime. Generally, a warning message is printed during compilation, and in the new modern IDEs there are warning icons displayed too as shown in the example below. Is there a simple example of how to use the deprecated attribute in C++? To deprecate a function, we can use […]
Make Member Function const and Global Function Static in Visual Studio Mryam Girmay September 14th, 20230 1 We are delighted to announce that Visual Studio Preview now includes the “Make Member Function Const” and “Make Global Function Static” features. To check out these features, make sure you update to the latest version of Visual Studio Preview. Download Visual Studio Preview Make Member Function Const Visual Studio now generates hints to mark member functions as const when a member function doesn’t modify the object’s state. This feature identifies cases where a member function performs actions that could be accomplished through the object’s public interface using a const pointer. We have made this process easier for you by adding a suggestion that allows you to make a member function const. When a member function can be made const, there will be a suggestion (indicated by three dots) below the function. Hovering over them will inform you that “the member function can be made const,” and you can click on the light bulb to make the member const. When you make a member function const, the change is applied to all the files that have the member function. You can preview all the changed files by selecting the “Preview all changed files” link. “Make Member Function Const” is on by default, and it is set as suggestion. The setting can be found and configured by navigating to Tools > Options > Text Editor > C/C++ > Code Style > Linter. Make Function Static In Visual Studio Preview, you’ll now receive hints to mark global functions as static. When encountering a global function that doesn’t have a forward declaration in a header file, you will be able to make the function static effortlessly. We already have a feature that detects global functions and suggests creating forward declarations, and now we have added an option to mark them as static. This feature works smoothly with modern C++ projects, as it doesn’t provide suggestions to make anonymous namespaces static. Static global functions are accessible within the translation unit where they are defined. When there is a global function that doesn’t have a forward declaration, it will have a suggestion. Hovering over the suggestion will reveal a screwdriver icon, signaling that the function can be made static. You can complete the process by clicking the screwdriver icon and selecting “Make this function static.” You can configure this feature’s setting in Tools > Options > Text Editor > C/C++ > IntelliSense. While the default tag is set as a suggestion, you have the flexibility to customize the severity level to none, warning, or error. Send us your feedback To experience this exciting new feature, make sure to download the latest version of Visual Studio Preview. Your feedback is of utmost importance to us, as it guides the enhancement of Visual Studio. Please share your insights in the comments section, the developer community, or on Twitter (@VisualC). Alternatively, you can also reach out to us via email at visualcpp@microsoft.com. Mryam Girmay Program Manager, C++ Follow
Hello C++ developers, this week we have five more professional and intermediate-level topics in modern C++. Modern C++ has many features to aid multi-thread programming that allow your applications to be faster and more responsive. Since the C++11 standard, the Concurrency Support Library includes built-in support for threads (std::thread) with atomic operations (std::atomic). In the first two post picks today, we explain how to allow atomics use in C++ signal handlers, plus we teach how to use atomic_flag. In another post, we explain how to use propagating exceptions. We also teach what the volatile keyword is and what it does. In the last post pick, we explain the concept of weak compare and exchange in modern C++. RAD Studio’s C++ Builder, Delphi, and their free community editions C++ Builder CE, and Delphi CE are a real force for modern application development. Our educational LearnCPlusPlus.org site has a whole bunch of new and unique posts with examples suitable for everyone from beginners to professionals alike. It is growing well thanks to you, and we have many new readers, thanks to your support! The site features a plethora of posts that are great for learning the features of modern C++ compilers with very simple explanations and examples. Table of Contents Where I can I learn C++ and test these examples with a free C++ compiler? How to use modern C++ with C++ Builder? How to learn modern C++ for free using C++ Builder? Do you want to know some more news about C++ Builder 12? Where I can I learn C++ and test these examples with a free C++ compiler? If you don’t know anything about C++ or the C++ Builder IDE, don’t worry, we have a lot of great examples on the LearnCPlusPlus.org website and they’re all completely free. Just visit this site and copy and paste any examples there into a new Console, VCL, or FMX project, depending on the type of post. We keep adding more C and C++ posts with sample code. In today’s round-up of recent posts on LearnCPlusPlus.org, we have new articles with very simple examples that can be used with: The free version of C++ Builder 11 CE Community Edition or a professional version of C++ Builder or free BCC32C C++ Compiler and BCC32X C++ Compiler or the free Dev-C++ Read the FAQ notes on the CE license and then simply fill out the form to download C++ Builder 11 CE. How to use modern C++ with C++ Builder? C++11 allows the use of atomics in signal handlers, and with the advent of C++ 17 the signal handler feature was again improved. The std::atomic_flag is an atomic boolean type that is guaranteed to be lock-free and can be used in signal handlers. Moreover, the header in C++ has an integer type std::sig_atomic_t that can be accessed as an atomic entity even in the presence of asynchronous interrupts made by signals. In our first post ğ,cl, we explain how to use atomic_flag in C++. In C++17, in addition to the std::atomic_flag in , the header has an integer type std::sig_atomic_t that can be accessed as an atomic entity even in the presence of asynchronous interrupts made by signals. In this next post, we explain how to use atomic_flag in C++. The C++11 standard offers the possibility of moving an exception from one thread to another. This type of movement is called propagating exceptions, exception propagation; also known as rethrow exception in multi-threading. To do that, some modifications have been […]
Integrating C++ header units into Office using MSVC (2/n) Cameron DaCamara Zachary Henkel September 11th, 20233 0 In this follow-up blog, we will explore progress made towards getting header units working in the Office codebase. Overview Overview: Where we were, where we’re going. Old Code, Old Problems: ‘fun’ code issues found while scaling out. Rethinking Compiler Tooling: How can the compiler rise to the scaling problems? A New Approach to Referencing an IFC. Playing Nice With Precompiled Headers (PCH). Selecting a Launch Project: REDACTED. Looking Ahead: Throughput. Overview Last time we talked about how and why header units can be integrated into a large cross-platform codebase like Office. We discussed how header units helped surface conformance issues (good) and expose and fix compiler bugs (good-ish). We talked about how we went about taking “baby steps” to integrate header units into smaller liblets—we’re talking something on the order of 100s of header units. This blog entry is all about scale and how we move from 100s of header units to 1000s of header units, including playing nicely with precompiled headers! Office’s header unit experiments continued by following the charge that we left you with in the last blog post: “Header Unit All the Things!”. From that perspective we were wildly successful! By the last count we were able to successfully create over 5000 header units from liblet public headers. The road to reach that milestone wasn’t always smooth, and we’ll cover some of the challenges. We’d like to highlight that the recent release of MSVC 17.6.6 makes this one of the best times to get started with header units! The release contains the full set of fixes that were discovered in cooperation with Office. The full set of fixes will also be available in 17.7.5 and 17.8 preview 2. Old Code, Old Problems While scaling out we encountered quite a number of complications. Some fixes involved updating Office code, while others needed to be solved on the compiler side. We’ll present just a few examples from each bucket. Symbolic Links The way Office sources coalesce is a mix between sources populated by git and libraries populated by NuGet packages which are then linked into a build source tree via symbolic links. From a build perspective, this is extremely convenient because you can decouple library updates from the sources and you can have one copy of library code shared across multiple copies of the git sources. Symbolic links are interesting from a compiler perspective for two reasons: diagnostics and #pragma once. For source locations, there are two options: use the symbolic link as the file name or use the physical file the link resolves to. When issuing diagnostics, the compiler tries to use the symbolic link location because that is what was provided on the /I line, but there are cases where you might want the physical file location. #pragma once is a whole other beast with respect to symbolic links. In the beginning, C-style include guards were created as a method of preventing repeated file content. #pragma once came about as a method of preventing inclusion of the same file. The distinction between file and content is part of the reason why #pragma once is difficult to standardize due to its reliance on filesystem vagaries to identify what it means to […]
Introduction: This post describes how to create and use Static Library (.Lib) and Dynamic (Run-Time) DLLs in C++ Builder. A library is a collection of pre-compiled code that can be re-used by programs. There are 2 types of libraries: static library and dynamic library. Static Library (.lib) vs Dynamic Library (.dll) A static library (.LIB file) (or archive) contains code that is linked to users’ programs at compile time. The executable file generated keeps its own copy of the library code. A dynamic library (.dll) (or shared library) contains code designed to be shared by multiple programs. The content in the library is loaded to memory at runtime. Each executable does not maintain its replication of the library. What are the differences between static and dynamic libraries? Static libraries (.lib), while reusable in multiple programs, are locked into a program at compile time. Dynamic (.dll), or shared libraries, on the other hand, exist as separate files outside of the executable file. C++ Builder Dynamic Library (.DLL) and Static (.Lib) Library Let’s jump right into creating a C++ Builder Dynamic Library (.DLL) This post is using C++ Builder 11.3 Steps: 1. File | New | Other | C++ Builder | Dynamic Library , select Source type = C++ , check Multi-Threaded, and select Target Framework = No Framework 2. Save the generated project to a new folder: File | Save Project As | New Folder | CppMyDLL (C:UsersamannarinoDocumentsEmbarcaderoStudioProjectsCppMyDLL). Rename project to CppMyDLL.cbproj, and rename Unit1.cpp to CppMyDLL.cpp 3. The generated CppMyDLL.cpp file has this code: extern “C” int _libmain(unsigned long reason) The _libmain function is the entry point into the dynamic library. When the dynamic library is loaded, the _libmain function is called. This function usually holds initialization code. 4. To be able to use the DLL and the Client .EXE on any computer (that does not have C++ Builder installed), use: Project | Options | C++ Linker | Link with Dynamic RTL = False And Packages | RunTime Packages | Link with Run Time Packages = False 5. Build the application (Project | Build). You should get a success Build and Link! 6. Your source code output folder: (C:Users/amannarino/Documents/Embarcadero/Studio/Projects/CppMyDLL/Win32/Debug) should have a CppMyDLL.dll (Dynamic Library) and a CppMyDLL.lib (Static Library). The Static Library (.lib) is automatically generated from the Dynamic Library (,dll). 7. A helpful free utility for seeing the contents of the DLL is Dependency Walker. Dependency Walker is a free utility that scans any 32-bit or 64-bit Windows module (exe, dll, ocx, sys, etc.) and builds a hierarchical tree diagram of all dependent modules. The Download link for Dependency Walker is: https://www.dependencywalker.com/ 8. Next, lets add a function to the CppMyDLL.cpp : double Sum(double a, double b) { return a +b; } Note: DLLs can contain functions that are hidden from the clients, and other functions that are public to the clients. 9. To make this Sum function visible to clients, we add: __declspec(dllexport) like this: double __declspec(dllexport) Sum(double a, double b) { 10. Using Dependency Walker this function SUM shows as @Sum$add To remove the characters @ and the $add (that descibes the function) we add extern “C” to the function, like this: extern “C” double __declspec(dllexport) Sum(double a, double b) { 11. Now, using Dependency Walker, the Sum function shows as: _Sum 12. To remove the […]
C++11 allows the use of atomics in signal handlers, and with the advent of C++ 17 the signal handler feature was again improved. The std::atomic_flag is an atomic boolean type that is guaranteed to be lock-free and can be used in signal handlers. Moreover, the header in C++ has an integer type std::sig_atomic_t that can be accessed as an atomic entity even in the presence of asynchronous interrupts made by signals. In this post, we explain how to use atomic_flag in C++. How to allow atomics use in C++ signal handlers? The header in C++ (or signal.h in C) has an an integer type std::sig_atomic_t that can be accessed as an atomic entity even in the presence of asynchronous interrupts made by signals. In this post, we explain how to allow atomics use in C++ signal handlers. Here is how we can use it: #include volatile sig_atomic_t flag = 0; Is there a full example of how to use atomics in C++ signal handlers? Here is an example that has a signal handler and uses sig_atomic_t flag from 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 #include #include volatile sig_atomic_t flag = 0; void handler(int signum) { flag = 1 ; } bool signal_check() { if ( signal( SIGINT, handler) == SIG_ERR ) { return false; } if (flag) std::cout
C++ is very strong in every aspect of modern programming. Volatile types are used with the volatile keyword. It is a lesser known type qualifier that is important to read types or objects whose value can be modified at any time. The volatile keyword is useful in memory-mapped applications, generally these are from a hardware device, from a sensor, from an input device, or data from on an IoT. For example, an application reading dynamic data from the registers of a medical robot and decides what to do with that robot arm. In this post we will explain the volatile keyword in C++ and how can we use volatile type specifier. What is volatile keyword in C++? Volatile types are declared with the volatile keyword with a type declaration. Here’s how it is used. volatile ; We can use volatile on standard types, structs, unions. We can use them with pointers too. Here are some examples of how to use the volatile keyword in C++. volatile int x; volatile unsigned long int *p; The volatile type specifier is used to change the variable whose values can be changed at any time and don’t have any constant value. The volatile qualifier is important to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Generally used in loops to read data, if you read those kinds of data without volatile types, the compiler and its optimizer can see the loop as useless. Your loop will never read the exact data in that time. For example, in this example: unsigned int x = 255; do { // … }while( x == 255 ); compiler optimization covert this as below: unsigned int x = 255; do { // … }while( true ); In other words, our loop becomes infinite by being true always even if the value of x is changed in some steps inside. To solve this, we can use volatile, thus we will keep reading data from x in do-while loop. Here is the example, volatile unsigned int x = 255; do { // … }while( x == 255 ); If you want to keep reading x data from that address, you must use volatile specifier for the x type. This is why the volatile specifier is needed when developing embedded systems or device drivers. If we need to read or write a memory-mapped hardware device, we can use volatile type specifier on these kinds of data. Because data on that device register could change at any time, so we need to use volatile keyword to ensure that we read data on that time and such accesses aren’t optimized away by the compiler. Another need is some processors have floating point registers that have more than 64 bits of precision and if you need consistency then you can force each operation to go back to memory by using the volatile keyword. Volatile specifier is also useful for some algorithms, such as Kahan summations, etc. Is there an example to use volatile keyword in C++? Assume that we have an address in our device or in a library of a driver, let’s set this address to a volatile […]
Invormațiile pe cale Dvs le introduceți în prezentul formular nu se păstrează online, dar se vor transmite direct la destinație. Mai multe informații găsiți în Politica Noastră de Confidentialitate
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.