This document contains code snippets and explanations of various C/C++ tricks and techniques, including Duff's device for loop unrolling, use of the [] operator, different swap algorithms, the --> operator, catching exceptions in initializer lists, namespace aliases, storage class specifiers, handling integer overflow, implicit and explicit type conversions, and named loops. It provides examples of these concepts along with brief descriptions on 59 pages.
HKG15-405: Redundant zero/sign-extension elimination in GCCLinaro
HKG15-405: Redundant zero/sign-extension elimination in GCC
---------------------------------------------------
Speaker: Kugan Vivekanandarajah
Date: February 12, 2015
---------------------------------------------------
★ Session Summary ★
Several instances of redundant zero/sign-extension related bugs are reported in GCC and Linaro bugzilla. These bugs are sources of performance/code size penalties. This presentation will discuss the history, design considerations, implementation, and performance characteristics of redundant zero/sign extension elimination in GCC. We will then discuss a new compiler pass that performs computation in promoted type mode in such a way that removes redundant zero/sign-extensions.
--------------------------------------------------
★ Resources ★
Pathable: https://hkg15.pathable.com/meetings/250833
Video: https://www.youtube.com/watch?v=JkTkmGe3tms
Etherpad: http://pad.linaro.org/p/hkg15-405
---------------------------------------------------
★ Event Details ★
Linaro Connect Hong Kong 2015 - #HKG15
February 9-13th, 2015
Regal Airport Hotel Hong Kong Airport
---------------------------------------------------
http://www.linaro.org
http://connect.linaro.org
HKG15-405: Redundant zero/sign-extension elimination in GCCLinaro
HKG15-405: Redundant zero/sign-extension elimination in GCC
---------------------------------------------------
Speaker: Kugan Vivekanandarajah
Date: February 12, 2015
---------------------------------------------------
★ Session Summary ★
Several instances of redundant zero/sign-extension related bugs are reported in GCC and Linaro bugzilla. These bugs are sources of performance/code size penalties. This presentation will discuss the history, design considerations, implementation, and performance characteristics of redundant zero/sign extension elimination in GCC. We will then discuss a new compiler pass that performs computation in promoted type mode in such a way that removes redundant zero/sign-extensions.
--------------------------------------------------
★ Resources ★
Pathable: https://hkg15.pathable.com/meetings/250833
Video: https://www.youtube.com/watch?v=JkTkmGe3tms
Etherpad: http://pad.linaro.org/p/hkg15-405
---------------------------------------------------
★ Event Details ★
Linaro Connect Hong Kong 2015 - #HKG15
February 9-13th, 2015
Regal Airport Hotel Hong Kong Airport
---------------------------------------------------
http://www.linaro.org
http://connect.linaro.org
Lab Manual IV (1).pdf on C++ Programming practiceranaibrahim453
C++ Programming C++ involves writing code to solve problems or create software applications using the C++ programming language. C++ is a powerful and versatile programming language widely used for developing system software, application software, device drivers, embedded software, and much more.Here are some key aspects of C++ programming:
Syntax: C++ syntax is similar to C, but with additional features such as classes, inheritance, polymorphism, templates, and more.
Object-Oriented Programming (OOP): C++ supports OOP, allowing you to organize code into classes and objects, encapsulate data, and implement inheritance, polymorphism, and abstraction.
Standard Template Library (STL): C++ includes a rich set of libraries called the Standard Template Library (STL), which provides containers (like vectors, lists, maps), algorithms (sorting, searching), and other utilities.
Memory Management: C++ gives you control over memory management, allowing you to allocate and deallocate memory using new and delete operators. However, this also means you need to manage memory carefully to avoid memory leaks and other issues.
Performance: C++ is known for its performance and efficiency. It allows low-level manipulation of resources, direct access to hardware, and efficient use of memory.
Platform Independence: C++ code can be compiled to run on different platforms, making it suitable for cross-platform development.
Compile-Time Polymorphism: C++ supports both compile-time polymorphism (achieved through function overloading and templates) and runtime polymorphism (achieved through inheritance and virtual functions).
Exceptions Handling: C++ provides exception handling mechanisms to deal with runtime errors and anomalies gracefully.
IO Streams: C++ offers powerful input/output capabilities through the use of IO streams, which provide a flexible and easy-to-use interface for reading from and writing to files, the console, and other sources.
Multi-threading: C++ has support for multi-threading, allowing you to create concurrent programs for better performance and responsiveness.
When programming in C++, it's essential to pay attention to memory management, avoid undefined behavior, and follow best practices to write efficient and maintainable code. Additionally, understanding the language's features and utilizing them effectively can lead to more robust and elegant solutions. If you have any specific questions or need help with a particular aspect of C++ programming, feel free to ask!Templates: C++ supports templates, allowing you to write generic code that works with any data type. Templates are powerful tools for creating reusable and flexible code.
Lambda Expressions: C++11 introduced lambda expressions, which provide a concise way to define anonymous functions. Lambdas are useful for writing inline functions, especially in algorithms and callback scenarios.
Smart Pointers: C++11 introduced smart pointers (std::unique_ptr, std::shared_ptr, std::weak_ptr), which h
Недавно работы комитета по стандартизации WG21 были завершены, и документ-черновик C++17 был отправлен на рассмотрение в Международную организацию по стандартизации (ISO). С этого момента технически можно считать, что стандарт C++17 у нас есть. Если вы ещё ознакомились с принятыми изменениями, то сейчас для этого самое время. В докладе будет сделан обзор нововведений. Рассмотрено текущее состояние дел у популярных компиляторов с поддержкой С++17
Go is, for all its C-esque syntax, is a relatively high-level language. There’s garbage collection, a type hierarchy, and even advanced concurrency primitives. Sometimes, though, you need access to lower-level control. Whether for performance, interoperability, or just for fun, the Cgo API is here to help! I will explain what it is, how to use it, and perhaps most importantly, when to avoid it.
A lot of Go programmers only experience with Cgo is when compilation fails with some obscure error. There’s a lot more to learn than that, and a lot of opportunities! I’ve personally used Cgo for writing Postgres foreign wrappers, and as a consumer when compiling Kubernetes.
Using Cgo can be a fun, rewarding experience. There are a lot of existing projects and libraries written in C, and calling them means not needing to reinvent the wheel. On the same face, if you have an existing project with a C API, calling Go can get you some of the higher-level Go niceness on top of the jagged C edges.
Some things I touch on:
* Calling Go from C
* Calling C from Go
* Memory management with Go objects in C
* Using C libraries from Go
* Real-world Cgo examples
* The pitfalls Go and dynamic linking
Programs are complete in best of my knowledge with zero compilation error in IDE Bloodshed Dev-C++. These can be easily portable to any versions of Visual Studio or Qt. If you need any guidance please let me know via comments and Always Enjoy Programming.
JavaScript is evolving. It’s an exciting time to be involved with this ubiquitous language of the web. Every year, we get exciting new features landing as part of the language. Let’s explore the freshly released features that were part of the 2019 ECMAScript specification. We’ll also briefly explore the process of how new features get proposed and added to the language, as well as the leading contenders expected to land in ES2020.
One of the most popular programming language on the market is getting even better. With every iteration of C# we get more and more features that are meant to make our lives as developers a lot easier. Join me in this session to explore what's new in C# 8, as well as what we can expect in the near (and far) future of C#!
We'll talk about:
- News in C# 8
- Pattern Matching (incl. Record Types)
- Nullable Reference Types and How to Avoid Null Reference Exceptions
- How Async & Await is Improving
Lab Manual IV (1).pdf on C++ Programming practiceranaibrahim453
C++ Programming C++ involves writing code to solve problems or create software applications using the C++ programming language. C++ is a powerful and versatile programming language widely used for developing system software, application software, device drivers, embedded software, and much more.Here are some key aspects of C++ programming:
Syntax: C++ syntax is similar to C, but with additional features such as classes, inheritance, polymorphism, templates, and more.
Object-Oriented Programming (OOP): C++ supports OOP, allowing you to organize code into classes and objects, encapsulate data, and implement inheritance, polymorphism, and abstraction.
Standard Template Library (STL): C++ includes a rich set of libraries called the Standard Template Library (STL), which provides containers (like vectors, lists, maps), algorithms (sorting, searching), and other utilities.
Memory Management: C++ gives you control over memory management, allowing you to allocate and deallocate memory using new and delete operators. However, this also means you need to manage memory carefully to avoid memory leaks and other issues.
Performance: C++ is known for its performance and efficiency. It allows low-level manipulation of resources, direct access to hardware, and efficient use of memory.
Platform Independence: C++ code can be compiled to run on different platforms, making it suitable for cross-platform development.
Compile-Time Polymorphism: C++ supports both compile-time polymorphism (achieved through function overloading and templates) and runtime polymorphism (achieved through inheritance and virtual functions).
Exceptions Handling: C++ provides exception handling mechanisms to deal with runtime errors and anomalies gracefully.
IO Streams: C++ offers powerful input/output capabilities through the use of IO streams, which provide a flexible and easy-to-use interface for reading from and writing to files, the console, and other sources.
Multi-threading: C++ has support for multi-threading, allowing you to create concurrent programs for better performance and responsiveness.
When programming in C++, it's essential to pay attention to memory management, avoid undefined behavior, and follow best practices to write efficient and maintainable code. Additionally, understanding the language's features and utilizing them effectively can lead to more robust and elegant solutions. If you have any specific questions or need help with a particular aspect of C++ programming, feel free to ask!Templates: C++ supports templates, allowing you to write generic code that works with any data type. Templates are powerful tools for creating reusable and flexible code.
Lambda Expressions: C++11 introduced lambda expressions, which provide a concise way to define anonymous functions. Lambdas are useful for writing inline functions, especially in algorithms and callback scenarios.
Smart Pointers: C++11 introduced smart pointers (std::unique_ptr, std::shared_ptr, std::weak_ptr), which h
Недавно работы комитета по стандартизации WG21 были завершены, и документ-черновик C++17 был отправлен на рассмотрение в Международную организацию по стандартизации (ISO). С этого момента технически можно считать, что стандарт C++17 у нас есть. Если вы ещё ознакомились с принятыми изменениями, то сейчас для этого самое время. В докладе будет сделан обзор нововведений. Рассмотрено текущее состояние дел у популярных компиляторов с поддержкой С++17
Go is, for all its C-esque syntax, is a relatively high-level language. There’s garbage collection, a type hierarchy, and even advanced concurrency primitives. Sometimes, though, you need access to lower-level control. Whether for performance, interoperability, or just for fun, the Cgo API is here to help! I will explain what it is, how to use it, and perhaps most importantly, when to avoid it.
A lot of Go programmers only experience with Cgo is when compilation fails with some obscure error. There’s a lot more to learn than that, and a lot of opportunities! I’ve personally used Cgo for writing Postgres foreign wrappers, and as a consumer when compiling Kubernetes.
Using Cgo can be a fun, rewarding experience. There are a lot of existing projects and libraries written in C, and calling them means not needing to reinvent the wheel. On the same face, if you have an existing project with a C API, calling Go can get you some of the higher-level Go niceness on top of the jagged C edges.
Some things I touch on:
* Calling Go from C
* Calling C from Go
* Memory management with Go objects in C
* Using C libraries from Go
* Real-world Cgo examples
* The pitfalls Go and dynamic linking
Programs are complete in best of my knowledge with zero compilation error in IDE Bloodshed Dev-C++. These can be easily portable to any versions of Visual Studio or Qt. If you need any guidance please let me know via comments and Always Enjoy Programming.
JavaScript is evolving. It’s an exciting time to be involved with this ubiquitous language of the web. Every year, we get exciting new features landing as part of the language. Let’s explore the freshly released features that were part of the 2019 ECMAScript specification. We’ll also briefly explore the process of how new features get proposed and added to the language, as well as the leading contenders expected to land in ES2020.
One of the most popular programming language on the market is getting even better. With every iteration of C# we get more and more features that are meant to make our lives as developers a lot easier. Join me in this session to explore what's new in C# 8, as well as what we can expect in the near (and far) future of C#!
We'll talk about:
- News in C# 8
- Pattern Matching (incl. Record Types)
- Nullable Reference Types and How to Avoid Null Reference Exceptions
- How Async & Await is Improving
The two-dimensional discrete wavelet transform (DWT) can be applied in the heart of many image-processing algorithms.
Until recently, several studies have compared the performance of such transform on parallel architectures, for example, on graphics
processing units (GPUs). All these studies however considered only separable calculation schedules.
Lifting Scheme Cores for Wavelet TransformDavid Bařina
The thesis focuses on efficient computation of the two-dimensional discrete wavelet transform. The state-of-the-art methods are extended in several ways to perform the transform in a single loop, possibly in multi-scale fashion, using a compact streaming core. This core can further be appropriately reorganized to target the minimization of certain platform resources. The approach presented here nicely fits into common SIMD extensions, exploits the cache hierarchy of modern general-purpose processors, and is suitable for parallel evaluation. Finally, the approach presented is incorporated into the JPEG 2000 compression chain, in which it has proved to be fundamentally faster than widely used implementations.
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
14. Integer promotion
char c = ’X’;
cout << c;
cout << +c;
David Barina C/C++ tricks April 13, 2018 14 / 59
15. Polyglot
$CC -std=c90 -pedantic -Wall -Wextra prog.c && ./a.out
I am compiled with C90
$CC -std=c99 -pedantic -Wall -Wextra prog.c && ./a.out
I am compiled with C99
$CC -std=c11 -pedantic -Wall -Wextra prog.c && ./a.out
I am compiled with C11 or newer
$CXX -std=c++98 -pedantic -Wall -Wextra prog.c && ./a.out
I am compiled with C++03 or older
$CXX -std=c++03 -pedantic -Wall -Wextra prog.c && ./a.out
I am compiled with C++03 or older
$CXX -std=c++11 -pedantic -Wall -Wextra prog.c && ./a.out
I am compiled with C++11 or newer
David Barina C/C++ tricks April 13, 2018 15 / 59
16. Polyglot
if( sizeof(’a’) == sizeof(char) )
{
// compiled with C++
}
else
{
// compiled with C
}
David Barina C/C++ tricks April 13, 2018 16 / 59
27. Member call on null pointer
class A {
int x;
public:
void foo() {
std:: cout << "foo" << std:: endl;
x = 0;
}
};
int main () {
A *a = 0;
a->foo ();
}
David Barina C/C++ tricks April 13, 2018 27 / 59
28. Member call on null pointer
class A {
int x;
public:
void foo() {
std:: cout << "foo" << std:: endl;
x = 0;
}
};
int main () {
A *a = 0;
a->foo ();
}
foo
Neopr´avnˇen´y pˇr´ıstup do pamˇeti (SIGSEGV)
David Barina C/C++ tricks April 13, 2018 27 / 59
29. Member call on null pointer
class A {
int x;
public:
void bar() {
std:: cout << "bar" << std:: endl;
}
};
int main () {
A *a = 0;
a->bar ();
}
David Barina C/C++ tricks April 13, 2018 28 / 59
30. Member call on null pointer
class A {
int x;
public:
void bar() {
std:: cout << "bar" << std:: endl;
}
};
int main () {
A *a = 0;
a->bar ();
}
bar
David Barina C/C++ tricks April 13, 2018 28 / 59
31. Integer overflow
int a = /* something */;
int b = /* something */;
a += b;
if( a < 0 ) {
/* ... */
}
David Barina C/C++ tricks April 13, 2018 29 / 59
32. Integer overflow
int a = /* something */;
int b = /* something */;
a += b; /* UB */
if( a < 0 ) { /* unreliable test */
/* ... */
}
David Barina C/C++ tricks April 13, 2018 30 / 59
33. Integer overflow
int a = /* something */;
int b = /* something */;
if( /* test */ ) {
/* ... */
}
a += b;
David Barina C/C++ tricks April 13, 2018 31 / 59
35. Integer overflow
int a = /* something */;
int b = /* something */;
addition ‘a + b‘
if( (b > 0) && (a > INT_MAX - b) )
/* would overflow */;
if( (b < 0) && (a < INT_MIN - b) )
/* would overflow */;
David Barina C/C++ tricks April 13, 2018 33 / 59
36. Integer overflow
int a = /* something */;
int b = /* something */;
subtraction ‘a - b‘
if( (b < 0) && (a > INT_MAX + b) )
/* would overflow */;
if( (b > 0) && (a < INT_MIN + b) )
/* would overflow */;
David Barina C/C++ tricks April 13, 2018 34 / 59
37. Integer overflow
int a = /* something */;
int b = /* something */;
multiplication ‘a * b‘
if( (b != 0) && (a > INT_MAX / b) )
/* would overflow */;
if( (b != 0) && (a < INT_MIN / b) )
/* would overflow */;
David Barina C/C++ tricks April 13, 2018 35 / 59
38. Integer overflow
int a = /* something */;
int b = /* something */;
multiplication ‘a * b‘
if( (b != 0) && (a > INT_MAX / b) )
/* would overflow */;
if( (b != 0) && (a < INT_MIN / b) )
/* would overflow */;
if( (a == -1) && (b == INT_MIN) )
/* would overflow */;
if( (b == -1) && (a == INT_MIN) )
/* would overflow */;
David Barina C/C++ tricks April 13, 2018 35 / 59
39. Integer overflow
int a = /* something */;
int b = /* something */;
division ‘a / b‘
if( (b == -1) && (a == INT_MIN) )
/* would overflow */;
David Barina C/C++ tricks April 13, 2018 36 / 59
43. Implicit type conversion
char a = 5;
int b = a; /* implicit type conversion */
David Barina C/C++ tricks April 13, 2018 40 / 59
44. Implicit type conversion
int a = 5;
char b = a; /* implicit type conversion */
David Barina C/C++ tricks April 13, 2018 41 / 59
45. Implicit type conversion
int a = 300;
char b = a; /* alter a value */
David Barina C/C++ tricks April 13, 2018 42 / 59
46. Implicit type conversion
int i = -1;
unsigned int u = i; /* change the sign */
David Barina C/C++ tricks April 13, 2018 43 / 59
47. Implicit type conversion
-Wconversion
warning: conversion to ‘int’ from ‘long int’
may alter its value
warning: conversion to ‘unsigned char’ from ‘int’
may alter its value
-Wsign-conversion
warning: negative integer implicitly converted
to unsigned type
warning: conversion to ‘unsigned int’ from ‘int’
may change the sign of the result
David Barina C/C++ tricks April 13, 2018 44 / 59
48. Explicit type conversion (cast notation)
int a = 5;
char b = (char)a; /* no warning */
std:: cout << +b << std:: endl; // 5
David Barina C/C++ tricks April 13, 2018 45 / 59
49. Explicit type conversion (conversion operator)
int a = 5;
char b = static_cast <char >(a);
std:: cout << +b << std:: endl; // 5
David Barina C/C++ tricks April 13, 2018 46 / 59
50. Explicit type conversion (cast notation)
int a = 5;
double *b = (double *)&a; /* no warning */
std:: cout << *b << std:: endl; // 2.47033e -323
David Barina C/C++ tricks April 13, 2018 47 / 59
51. Explicit type conversion (conversion operator)
int a = 5;
double *b = static_cast <double *>&a;
error: invalid static_cast from type ‘int*’
to type ‘double*’
David Barina C/C++ tricks April 13, 2018 48 / 59
52. Explicit type conversion (conversion operator)
int a = 5;
double *b = reinterpret_cast <double *>(&a);
std:: cout << *b << std:: endl; // 2.47033e -323
David Barina C/C++ tricks April 13, 2018 49 / 59
53. Explicit type conversion
( new_type ) expression
const_cast<new_type>(expression)
static_cast<new_type>(expression)
static_cast followed by const_cast
reinterpret_cast<new_type>(expression)
reinterpret_cast followed by const_cast
David Barina C/C++ tricks April 13, 2018 50 / 59
54. Explicit type conversion (cast notation)
-Wold-style-cast
warning: use of old-style cast
David Barina C/C++ tricks April 13, 2018 51 / 59
55. Initializer lists
class A {
int i;
public:
A() { i = 0; } // default
A(int i_) { i = i_; } // init
A& operator =(int i_) { i = i_; } // init
};
class B {
A a;
public:
B() { a = 3; } // default , init
};
David Barina C/C++ tricks April 13, 2018 52 / 59
56. Initializer lists
class A {
int i;
public:
A() { i = 0; } // default
A(int i_) { i = i_; } // init
A& operator =(int i_) { i = i_; } // init
};
class B {
A a;
public:
B() : a(3) {} // init
};
David Barina C/C++ tricks April 13, 2018 53 / 59
57. const member
class A {
public:
const int i;
A(int i_) { i = i_; }
};
error: assignment of read-only member ‘A::i’
David Barina C/C++ tricks April 13, 2018 54 / 59
58. const member
class A {
public:
const int i;
A(int i_) : i(i_) {}
};
David Barina C/C++ tricks April 13, 2018 55 / 59
59. const member
class A {
public:
const int i;
A(int i_) : i(i_) {}
A& operator =( const A& a) {
i = a.i;
return *this;
}
};
error: assignment of read-only member ‘A::i’
David Barina C/C++ tricks April 13, 2018 56 / 59
60. const member
class A {
public:
const int i;
A(int i_) : i(i_) {}
A& operator =( const A& a) {
return *new(this) A(a);
}
};
A a(3);
a = A(4);
std:: cout << a.i << std:: endl; /* UB */
David Barina C/C++ tricks April 13, 2018 57 / 59
61. const member
class A {
public:
const int i;
A(int i_) : i(i_) {}
A& operator =( const A& a) {
return *new(this) A(a);
}
};
A a(3);
std:: cout << (a = A(4)).i << std:: endl;
David Barina C/C++ tricks April 13, 2018 58 / 59
62. const member (C++17)
class A {
public:
const int i;
A(int i_) : i(i_) {}
A& operator =( const A& a) {
return *new(this) A(a);
}
};
A a(3);
a = A(4);
std:: cout << std:: launder (&a)->i << std:: endl;
David Barina C/C++ tricks April 13, 2018 59 / 59