×

Attributes in C

Attributes are one of modern C++ key features. It is the process by which initiator can add more information to the language instead of introducing new keywords for every attribute. It helps to decorate a code accomplishment in C, and C++ languages. Some of these attributes are written in standard syntax[[at]] and some are in non-standard syntax.

Syntax:

identifier: [[indication]]

Except some specific ones, almost all the attributes can be adapted with functions, classes structures etc.

Purpose of attributes in C++

Conditions to be imposed on code:

To meet the execution needs, the constraints in the C language are referred to a condition and in the updated versions of C++, the code for describing conditions is written in this way.

int f (int i)
{
if (i>0)
           return i;
else:
           return -1;
       //code
}

It enhances the code understandability,and it avoids the misconception in the code that is written inside the code function for the checking of the arguments.

int f (int i) [[expects: i>0]]
              {
                    //code
}

To provide extra information to the compiler for expansion purposes:

Compilers are good at expansion but compare to humans; they lag at some places and propose a code which is insufficient. The main reason behind this the information which is to get on has been lacked off. about the problem which humans have. To overcome this problem, the C++ has introduced a new way with adding new attributes to it and the code for the implementation of the attributes is:

int f (int i)
{
      switch(i) {
      case 1:
           [[fall through]];
           [[likely]] case 2: return 1;
       }
       return -1;
  }

The overall performance of the code totally depends on the compiler. When the statements are headed by the compiler, the performance automatically improves. Examples of some such attributes are:

For example:

[carries_ dependency], [likely], [unlikely]

Overcoming some of the warnings and errors that the users have in the code

When a user deploy a code, in some cases, the user intentionally overwrites the wrong code with some mistakes and it results in errors which is identified by the complier and one such case arises in the switch and break statements

For example:

#include<iostream>
#include <string>


int main ()
{
       //setting debugging mode in compiler or ‘R’
       [[maybe unused]] char mg_brk = ‘D’;


      //compiler does not release errors on unused variables
}

List of standard attributes in C++

C++11

1. no return:This indicates function that doesn’t return value

Usage:

[[no return]] void f ();

If a function contains void type, it returns to caller without any value but in the case of an infinity loop, it does not return to caller but adding a no return provides hints to compiler to expand code.

Following is an example code which provides clearcut information,

#include<iostream>
           #include<string>
           [[no return]] void f ()
           {


}
void g ()
             {
std: count << “code is intended to reach here”;
}
               int main ()
               {
                     f ();
                      g ();
                 }

Warning:

main.cpp: In function ‘void f ()’ :

     main.cpp: warning: ‘no return’ function does return

           }

C++14

2. deprecated: It indicates that name declared with this attribute became antiquated and must not be used for specific reason. It can be applied to namespace, functions, and classes.

Usage:

[[deprecated (“reason for deprecation”)]]


           // for class/struct/union
struct [[deprecated]] s;


//for functions
           [[deprecated]] void f ();


           //for namespaces
Namespace [[deprecated]] ns {}


//for variables 
           [[deprecated]] int x;

Example:

#include<iostream>
                 #include<string>
                 [[deprecated (“Susceptible to buffer overflow”)]] void gets(char* str)
                 {


                  }
void gets-n(std::string& str)
{
                          char st[100];
std::cout<< “Successfully Executed”;
std::cin.getline(st, 100);
str= std:: string(st);
                     }
                     int main ()
{
                              char a [100];
                               gets (a);
                     }

Warning:

main.cpp: in function ‘int main ()’ :

                      main.cpp: warning: ‘void gets(char*)’ is deprecated:

         Susceptible to buffer overflow [-Wdeprecated-declarations]

                                             gets (a);

C++17

3. no discard: The difference between the no discard with function and no discard with class is that, in case of function no discard is applied to function which declares as no discard but in class, it is applied to each function which return no discard entity by value.

Usage:


// functions
      [[no discard]] void f ();


      //class/struct declaration
       Struct [[no discard]] my -struct {};

Example:

#include<iostream>
#include<string>


       //value which returns must be used by caller
       [[no discard]] int f ()
        {
                      return 0;
 }  


            class [[no discard]] my _ class {};
            my _ class fun ()
            {
return my _ class ();
             }


int main ()
              {
                        int x {1};


                        // as value is used no error
                       // x=f();


                      // error: value is not used
                       f ();
                       // value not used error
                       // fun ();


                       return x;
}

Warning:

prog.cpp:warning: ‘no discard’ attribute ignores [-Wattributes]

          [[no discard]] int f ()

    prog.cpp: warning: ‘no discard’ attribute directive ignores [-wattributes]

            class [[no discard]] my _ class {};

4. maybe _ unused: It isused to summarize warnings on any unused object.

    Usage:

//variables
          [[ maybe_ used]] bool log _ var = true;
         //functions
         [[maybe_ unused]] void log_ without_ warning ();


         //function arguments
         Void f ([[maybe_ unused]] int a, int b);

Example:

#include<iostream>
          #include<string>
          int main ()
          {
[[maybe_ unused]] char mg_brk = ‘D’;


           }

Related Topics

Compilation Process in C language

What is the Compilation Process?  The compilation is a method whereby the source code is converted into object code. It is achieved with compiler assistance. The compiler tests the source code for syntactic...

3 minutes read.

How to use atoi() function in C

Introduction: The atoi() is a function used in C programming language. This function converts string characters to the integer value. The atoi() function converts the input string to the return type of...

4 minutes read.

Binomial Coefficient Program in C

What is Binomial coefficient? In the given set of n possibilities, the binomial coefficient(n,k) indicates the order of choosing 'K' results from those possibilities. Binomial coeeficient of posistive n and k...

3 minutes read.

Break, continue and goto statement in C

Break statement Break statement is used to break the process of a loop (while, do while and for) and switch case. Syntax: break; Example 1 while(test Expression) { // codes if(condition for break){ break; } // codes } Example 2 For(int it, condition,...

1 minute read.

Actual and Formal Parameters

Any variable declared within the parenthesis is referred to as the parameters during the function declaration. Parameters tell the function about the argument datatype, their order, and the number of...

5 minutes read.

Difference between while and for loop in C

While Loop The syntax that can be used for the ‘while’ loop in the C programming language is mentioned below: while (test expression or termination condition)  {   // the main body of the...

6 minutes read.

Difference between Array and List in C

C# Array vs List is where the abstraction and implementation of human computing meet.  Arrays are incredibly related to the hardware concept of contiguous and contiguous memory, where each part is...

3 minutes read.

Sizeof in C

A pointer in C is defined as a variable that stores the information of the address of another variable. A pointer can be incremented or decremented, which means we can...

4 minutes read.

While Loop in C programming examples

Introduction There is always a header file containing all the essential data regarding inputs and outputs of various functions in the C programs. The following statement describes how to use/add header file...

22 minutes read.

Scope of variables in C

Introduction The scope of variables in C can be defined as the scope of reach of a variable, the term scope is used to determine the visible range of an object....

4 minutes read.

strcat() Function in C

Strings in c: A string is defined as the set of characters that are enclosed within the double quotations (" "). The String always ends with the null character ("\0"). The...

3 minutes read.

Memory leak in C

What is memory leak in C? Memory leak occurs when we keep allocating memory in the heap without freeing it, i.e., the allocated memory in heap is not released back to...

3 minutes read.

Control statement in C

What is a control statement? A control statement helps us to control the flow of the program. The control statement helps us to execute the program's instructions in a user-defined order....

8 minutes read.

User Defined Functions in C

C Functions: A function is defined as a block of code that is used to perform some specific task. In functions, we use flower brackets ({}) which contain the set of programming...

5 minutes read.

Isalnum() function in C

Introduction: The isalnum () is a function used in C programming language. This function checks the passing number or argument is an alphanumeric number or not. The alphanumeric number consists of the...

3 minutes read.

How to delete a file in C

A file is a group of data kept on a secondary device, such as a hard disc. It is typically utilized as a real-world application with a lot of data. These...

3 minutes read.

Round Robin Scheduling in C

Round Robin Scheduling in C Round robin is a CPU (Central Processing Unit) scheduling algorithm designed to share the time systems. It is one of the simplest and easiest scheduling algorithms...

4 minutes read.

Derived Data Types in C

A variable in a program occupies some space in the computer's memory where some value is stored. Each variable in C has an associated data type. A value to be...

4 minutes read.

Fee Management System in C

The concept is to split every operation into its very own characteristic. Software is made from all of the capabilities mixed with transfer cases. An example of the capabilities may...

5 minutes read.

Diffie-Hellman Algorithm in C

Background: A method of public-key encryption known as elliptic curve cryptography (ECC) is based on the algebraic structure of elliptic curves over finite fields. To ensure equal security, ECC encryption requires fewer...

4 minutes read.