×

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

What is Linked List in C

Linked list Similar to an array, a linked list is a linear data structure that stores a chain of nodes with two fields of memory in each node. Where first memory...

7 minutes read.

If Statement in C

Decision Control Statements We frequently desire one set of instructions to be carried out in one circumstance while another set of instructions to be carried out in a completely different circumstance....

3 minutes read.

Palindrome Number in C

What is a Palindrome? A number that doesn't change when reversed is known as a palindrome. We reverse a number and compare it to the original number to determine whether it is...

4 minutes read.

Dangling pointers in C

Dangling pointers in C: A pointer is a variable that stores the memory address of other variables. The pointers may also store the address of other’s memory items. They are...

4 minutes read.

Type qualifiers in C

Type qualifiers in C: In the C programming language, type qualifiers are the keywords that prepend to the variables to change their accessibility, i.e., we can tell that the type...

4 minutes read.

Use of free() function in C

Introduction The free() function uses in C programming language. The free() function in the C programming language uses to release or deallocate the memory blocks; these blocks are previously allocated by calloc(), malloc() or realloc()...

3 minutes read.

Remove an element from an array in C

A collection of objects or pieces of the same data type stored in a single memory block is known as an array. A data structure called an array is used...

3 minutes read.

Data Structures And Algorithms in C

C language is one of the most flexible and simple languages. So, it is always better to learn any concept in C language compared to other languages. Let us look...

13 minutes read.

Assert() Function in C

Assert (): In C, the statements are executed with the exit statement. In C language declare, and it tests the condition parameters. If the statement executed will be false, it shows...

4 minutes read.

Local Labels in C

Anyone who has written programs in the C programming language is required to be familiar with the "go to" and "labels" used in C to navigate between functions. "Local labels"...

4 minutes read.

C Language Environment Setup

To compile C program, we must have GCC compiler installed on our machine. In this C tutorial, all the examples are compiled and tested using GCC compiler. Although we can...

3 minutes read.

Armstrong program in C using function

In this article we will learn how to find Armstrong of a number using function in C. An Armstrong number is a three-digit number that is the sum of its separate...

1 minute read.

Flow chart of While loop in C

This is a flowchart that represents the process of executing the while loop in the C programming language.Generally, as we know there are three main components of while loop:1. The...

3 minutes read.

Escape Sequence in C

An escape sequence is a sequence of character that used inside the string literal or character.  All the escape sequence is used with the backslash (\) symbol. The list of an...

1 minute read.

Prime Number code in C

Prime Number Programs in C language In this tutorial, we will learn how to check whether the given number is a prime number or not, and how to print all the...

4 minutes read.

Typecast vs. typedef in C

Typecast vs. typedef in C Typecast In the C programming language, converting the data type from one form to another is known as type casting or the type conversion. It is a...

5 minutes read.

Multilevel Feedback Queue Scheduling (MLFQ) CPU Scheduling

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.

Fibonacci series program in C using Recursion

In this tutorial, we’ll explore how to utilise recursion to build the Fibonacci sequence in C language. What does the term "Fibonacci Series" mean? The following number in a Fibonacci number series is...

2 minutes read.

Advantages of Dynamic Memory Allocation in C

Dynamic Memory Allocation Dynamic memory allocation is a process of assigning or allocating memory to a variable during the execution of a program. Dynamic memory allocation provides storage according to the...

3 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.