Attributes in C++In modern C++ language, we have the features of using attributes which increases the efficiency of the code and reduces the time for the programmer to write huge code. Attributes in C++ are like some additional condition which is written with the code, and the compiler is bound to follow that particular condition. These attributes can be any condition or any information attached to variables or functions. Although compilers are pretty effective at optimization, they nevertheless fall short in several areas when compared to humans and recommend inefficient generalized code. This primarily occurs as a result of a lack of understanding regarding the "issue" that person faces. The C++ standard has included specific new properties that enable a small amount of additional specification to the compiler rather than the actual code statement in order to somewhat alleviate this issue. Syntax: There are the following attributes used in the C++ code: 1. noreturn attributeThis attribute is used before any function declaration, and this attribute represents that this function will never return any value. Since we have a void keyword which works on the same functionality but the key difference is that a void function does not return any value. Still, the controller returns back to the function call whereas in the noreturn attribute, controller does not return to the point where the function was called. C++ Example: Output: Explanation: In the above example, fxn1 has a void return type, so it does not return any value, but after calling fxn1, fxn2 will be called because the controller will reach to the point where fxn1 was called. C++ Example 2: Output: Explanation: In the above code, if we use the noreturn attribute before fxn1 then we will see the warning in the compiler about the attribute. 2. maybe_unused attributeThis attribute is used to ignore the warning of the compiler when we declare any variable in the code and do not use it. C++ Example: Output: Explanation: In the above example, we have an unused variable "a". Still, the compiler will not throw any error or any warning regarding this unused variable because we have used the attribute before the variable name. 3. nodiscard attributeThis attribute is used before any function, and the return value of that function cannot be discarded. C++ Example: Output: Explanation: In the above example, we have 0 as the return value from function f, and we will take it into variable x, so we have utilized the return value, and there will be no error. C++ Example 2: Output: Explanation: In the above code, we have discarded the return value from the function f, and attribute nodisacrd is used before the function, so it will throw an error that we cannot discard the value of the variable. 4. likely attributeThis attribute is used before those conditional statements which have more probability of execution. C++ Example: Output: Difference between Standard and Non-standard Attributes
|