C

 



The C programming language is a general-purpose programming language that was developed in the early 1970s by Dennis Ritchie at Bell Labs. 
It has been widely used in systems programming, application development, and various other domains due to its simplicity, efficiency, and portability. 


In C Programming language, there are many rules so to avoid different types of errors. One of such rule is not able to declare variable names with auto, long, etc. This is all because these are keywords. Let us check all keywords in C language.

What are Keywords?
Keywords are predefined or reserved words that have special meanings to the compiler. These are part of the syntax and cannot be used as identifiers in the program. A list of keywords in C or reserved words in the C programming language are mentioned below:



auto is the default storage class variable that is declared inside a function or a block. auto variables can only be accessed within the function/block they are declared. By default, auto variables have garbage values assigned to them. Automatic variables are also called local variables as they are local to a function. 

auto int num;
Here num is the variable of the storage class auto and its type is int. Below is the C program to demonstrate the auto keyword:



// C program to demonstrate
// auto keyword
#include <stdio.h>
 
int printvalue()
{
  auto int a = 10;
  printf("%d", a);
}
 
// Driver code
int main()
{
  printvalue();
  return 0;
}
Output
10
break and continue
The break statement is used to terminate the innermost loop. It generally terminates a loop or a switch statement. The switch statement skips to the next iteration of the loop. Below is the C program to demonstrate break and continue in C:


// C program to show use
// of break and continue
#include <stdio.h>
 
// Driver code
int main()
{
  for (int i = 1; i <= 10; i++)
  {
    if (i == 2)
    {
      continue;
    }
    if (i == 6)
    {
      break;
    }
    printf("%d ", i);
  }
  return 0;
}
Output
1 3 4 5 
switch, case, and default
The switch statement in C is used as an alternate to the if-else ladder statement. For a single variable i.e, switch variable it allows us to execute multiple operations for different possible values of a single variable. 

switch(Expression)
{
    case '1': // operation 1
            break;
    case:'2': // operation 2
            break;
    default: // default statement to be executed 
}
Below is the C program to demonstrate the switch case statement:


// C program to demonstrate
// switch case statement
#include <stdio.h>
 
// Driver code
int main() {
  int i = 4;
  switch (i) {
    case 1:
      printf("Case 1\n");break;
    case 2:
      printf("Case 2\n");break;
    case 3:
      printf("Case 3\n");break;
    case 4:
      printf("Case 4\n");break;
    default:
      printf("Default\n");break;
  }
}
Output
Case 4

Note: it is best to add a break statement after every case so that switch statement doesn’t continue checking the remaining cases.

Output
Case 4
Default
char
char keyword in C is used to declare a character variable in the C programming language.

char x = 'D';
Below is the C program to demonstrate the char keyword:


// C program to demonstrate
// char keyword
#include <stdio.h>
 
// Driver code
int main() {
  char c = 'a';
  printf("%c", c);
  return 0;
}
Output
a
const
The const keyword defines a variable who’s value cannot be changed.

const int num = 10;
Below is the C program to demonstrate the const keyword:


// C program to demonstrate
// const keyword
#include <stdio.h>
 
// Driver code
int main() {
  const int a = 11;
  a = a + 2;
  printf("%d", a);
  return 0;
}
This code will produce an error because the integer a was defined as a constant  and it’s value was later on changed.
Output:

error: assignment of read-only variable 'a'
       a = a + 2;
do
The do statement is used to declare a do-while loop. A do-while loop is a loop that executes once, and then checks it’s condition to see if it should continue through the loop. After the first iteration, it will continue to execute the code while the condition is true.

Below is the C program to demonstrate a do-while loop.


// C program to demonstrate
// do-while keyword
#include <stdio.h>
 
// Driver code
int main()
{
  int i = 1;
  do {
    printf("%d ", i);
    i++;
  } while(i <= 5);
   
  return 0;
}
Output
1 2 3 4 5 
double and float
The doubles and floats are datatypes used to declare decimal type variables. They are similar, but doubles have 15 decimal digits, and floats only have 7.

Example:

float marks = 97.5;
double num;
Below is the C program to demonstrate double float keyword:


// C program to demonstrate
// double float keyword
#include <stdio.h>
 
// Driver code
int main() {
  float f = 0.3;
  double d = 10.67;
  printf("Float value: %f\n", f);
  printf("Double value: %f\n", d);
  return 0;
}
Output
Float value: 0.300000
Double value: 10.670000

if-else
The if-else statement is used to make decisions, where if a condition is true, then it will execute a block of code; if it isn’t true (else), then it will execute a different block of code.

if(marks == 97) {
    // if marks are 97 then will execute this block of code
}
else {
    // else it will execute this block of code
}
Below is the C program to demonstrate an if-else statement:


// C program to demonstrate
// if-else keyword
#include <stdio.h>
 
// Driver code
int main()
{
  int a = 10;
  if(a < 11)
  {
    printf("A is less than 11");
  }
  else
  {
    printf("A is equal to or "
           "greater than 11");
  } 
  return 0;
}
Output
A is less than 11
enum
The enum keyword is used to declare an enum (short for enumeration). An enum is a user-defined datatype, which holds a list of user-defined integer constants. By default, the value of each constant is it’s index (starting at zero), though this can be changed. You can declare an object of an enum and can set it’s value to one of the constants you declared before. Here is an example of how an enum might be used:


// An example program to
// demonstrate working of
// enum in C
#include<stdio.h>
 
// enum declaration:
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
 
// Driver code
int main()
{
//object of the enum (week), called day
  enum week day;
  day = Wed;
  printf("%d", day);
  return 0;
}
Output
2
extern
The extern keyword is used to declare a variable or a function that has an external linkage outside of the file declaration.


#include <stdio.h>
 
extern int a;
 
int main(){
   
    printf("%d", a);
 
      return 0;
}
for
The “for” keyword is used to declare a for-loop. A for-loop is a loop that is specified to run a certain amount of times.

Below is the C program to demonstrate a for-loop: 


// C program to demonstrate
// for keyword
#include <stdio.h>
 
// Driver code
int main()
{
  for (int i = 0; i < 5; i++)
  {
    printf("%d ", i);
  }
  return 0;
}
Output
0 1 2 3 4 
goto
The goto statement is used to transfer the control of the program to the given label. It is used to jump from anywhere to anywhere within a function.

Example:

goto label;

// code

label:
Below is the C program to demonstrate the goto keyword:

C

// C program demonstrate
// goto keyword
#include <stdio.h>
 
// Function to print numbers
// from 1 to 10
void printNumbers() {
    int n = 1;
 
label:
    printf("%d ", n);
    n++;
    if (n <= 10) goto label;
}
 
// Driver code
int main(){
    printNumbers();
    return 0;
}
Output
1 2 3 4 5 6 7 8 9 10 
int
int keyword is used in a type declaration to give a variable an integer type. In C, the integer variable must have a range of at least -32768 to +32767. 

Example:

int x = 10;
Below is the C program to show the int keyword:

C

// C program to demonstrate
// int keyword
#include <stdio.h>
 
void sum() {
    int a = 10, b = 20;
    int sum;
    sum = a + b;
    printf("%d", sum);
}
 
// Driver code
int main() {
    sum();
    return 0;
}
Output
30
short, long, signed, and unsigned
Different data types also have different ranges up to which they can store numbers. These ranges may vary from compiler to compiler. Below is a list of ranges along with the memory requirement and format specifiers on the 32-bit GCC compiler.

Data Type

Memory (bytes)

Range

Format Specifier

short int 

2

-32,768 to 32,767 

%hd 

unsigned short int 

2  

0 to 65,535

%hu

unsigned int 


0 to 4,294,967,295 

%u 

long int 


-2,147,483,648 to 2,147,483,647

%ld 

unsigned long int


0 to 4,294,967,295 

%lu

long long int  

8

-(2^63) to (2^63)-1 

%lld 

unsigned long long int

8

0 to 18,446,744,073,709,551,615

%llu 

signed char

1

-128 to 127 

%c

unsigned char 

1

0 to 255 

%c

long double

16

3.4E-4932 to 1.1E+4932

%Lf 

Below is the C program to demonstrate the short, long, signed, and unsigned keywords:

C

// C program to demonstrate
// short, long, signed,
// and unsigned keyword
#include <stdio.h>
 
// Driver code
int main() {
  // short integer
  short int a = 12345;
   
  // signed integer
  signed int b = -34;
   
  // unsigned integer
  unsigned int c = 12;
   
  // L or l is used for
  // long int in C.
  long int d = 99998L;
   
  printf("Integer value with a short int data: %hd", a);
  printf("\nInteger value with a signed int data: %d", b);
  printf("\nInteger value with an unsigned int data: %u", c);
  printf("\nInteger value with a long int data: %ld", d);
  return 0;
}
Output
Integer value with a short int data: 12345
Integer value with a signed int data: -34
Integer value with an unsigned int data: 12
Integer value with a long int data: 99998
return
The return statement returns a value to where the function was called.

Example:

return x;
Below is the C program to demonstrate the return keyword:

C

// C program to demonstrate
// return keyword
#include <stdio.h>
int sum(int x, int y) {
  int sum;
  sum = x + y;
  return sum;
}
 
// Driver code
int main() {
  int num1 = 10;
  int num2 = 20;
  printf("Sum: %d",
          sum(num1, num2));
  return 0;
}
Output
Sum: 30
sizeof 
sizeof is a keyword that gets the size of an expression, (variables, arrays, pointers, etc.) in bytes.

Example:

sizeof(char);
sizeof(int);
sizeof(float); in bytes.
Below is the C program to demonstrate sizeof keyword:

C

// C program to demonsstrate
// sizeof keyword
#include <stdio.h>
 
// Driver code
int main() {
  int x = 10;
  printf("%d", sizeof(x));
  return 0;
}
Output
4
register
Register variables tell the compiler to store variables in the CPU register instead of memory. Frequently used variables are kept in the CPU registers for faster access. 

Example: 

register char c = 's'; 
static 
The static keyword is used to create static variables. A static variable is not limited by a scope and can be used throughout the program. It’s value is preserved even after it’s  scope.

For Example:

static int num;
struct 
The struct keyword in C programming language is used to declare a structure. A structure is a list of variables, (they can be of different data types), which are grouped together under one data type.

For Example:

struct Geek {
    char name[50];
    int num;
    double var;
};
Below is the C program for the struct keyword:

C

// C program to demonstrate
// struct keyword
#include <stdio.h>
#include <string.h>
 
struct Books {
  char  title[50];
  char  author[50];
};
 
// Driver code
int main( ) {
  // Declare Book1 of type Book
  struct Books book1;       
    
 // book 1 specification
 strcpy(book1.title, "C++ Programming");
 strcpy(book1.author, "Bjarne Stroustrup");
  
 // Print book details
 printf("Book 1 title : %s\n", book1.title);
 printf("Book 1 author : %s\n", book1.author);
 return 0;
}
Output
Book 1 title : C++ Programming
Book 1 author : Bjarne Stroustrup

typedef 
The typedef keyword in C programming language is used to define a data type with a new name in the program. typedef keyword is used to make our code more readable.

For Example:

typedef long num
In this example we have changed the datatype name of “long” to “num”.

union 
The union is a user-defined data type. All data members which are declared under the union keyword share the same memory location.

Example:

union GeekforGeeks {
    int x;
    char s;
} obj;
Below is the C program for the union keyword:

C

#include <stdio.h>
union student { 
  int age; 
  char marks;  
} s; 
 
// Driver code
int main() { 
  s.age = 15; 
  s.marks = 56;
  printf("age = %d", s.age); 
  printf("\nmarks = %d", s.marks); 
}
Output
age = 56
marks = 56
void 
The void keyword means nothing i.e, NULL value. When the function return type is used as the void, the keyword void specifies that it has no return value.

Example:

void fun() {
    // program
}
volatile
The volatile keyword is used to create volatile objects. Objects which are declared volatile are omitted from optimization as their values can be changed by code outside the scope of the current code at any point in time.

For Example:

const volatile marks = 98;
marks are declared constant so they can’t be changed by the program. But hardware can change it as they are volatile objects.

What are the Most Important Features of C Language?

Here are some of the most important features of the C language:

  1. Procedural Language
  2. Fast and Efficient
  3. Modularity
  4. Statically Type
  5. General-Purpose Language
  6. Rich set of built-in Operators
  7. Libraries with Rich Functions
  8. Middle-Level Language
  9. Portability
  10. Easy to Extend
     

features of C programming language

Let discuss these features one by one:

1. Procedural Language

In a procedural language like C step by step, predefined instructions are carried out. C program may contain more than one function to perform a particular task. New people to programming will think that this is the only way a particular programming language works. There are other programming paradigms as well in the programming world. Most of the commonly used paradigm is an object-oriented programming language. 

2. Fast and Efficient

Newer languages like Java, python offer more features than c programming language but due to additional processing in these languages, their performance rate gets down effectively. C programming language as the middle-level language provides programmers access to direct manipulation with the computer hardware but higher-level languages do not allow this. That’s one of the reasons C language is considered the first choice to start learning programming languages. It’s fast because statically typed languages are faster than dynamically typed languages.

3. Modularity

The concept of storing C programming language code in the form of libraries for further future uses is known as modularity. This programming language can do very little on its own most of its power is held by its libraries. C language has its own library to solve common problems.

4. Statically Type

C programming language is a statically typed language. Meaning the type of variable is checked at the time of compilation but not at run time. This means each time a programmer types a program they have to mention the type of variables used.

5. General-Purpose Language

From system programming to photo editing software, the C programming language is used in various applications. Some of the common applications where it’s used are as follows: 

6. Rich set of built-in Operators

It is a diversified language with a rich set of built-in operators which are used in writing complex or simplified C programs.

7. Libraries with Rich Functions

Robust libraries and functions in C help even a beginner coder to code with ease.

8. Middle-Level Language

As it is a middle-level language so it has the combined form of both capabilities of assembly language and features of the high-level language.

9. Portability

C language is lavishly portable as programs that are written in C language can run and compile on any system with either no or small changes. 

10. Easy to Extend

Programs written in C language can be extended means when a program is already written in it then some more features and operations can be added to it.



Introduction:

The C programming language has several standard versions, with the most commonly used ones being C89/C90, C99, C11, and C18.

  1. C89/C90 (ANSI C or ISO C) was the first standardized version of the language, released in 1989 and 1990, respectively. This standard introduced many of the features that are still used in modern C programming, including data types, control structures, and the standard library.
  2. C99 (ISO/IEC 9899:1999) introduced several new features, including variable-length arrays, flexible array members, complex numbers, inline functions, and designated initializers. This standard also includes several new library functions and updates to existing ones.
  3. C11 (ISO/IEC 9899:2011) introduced several new features, including _Generic, static_assert, and the atomic type qualifier. This standard also includes several updates to the library, including new functions for math, threads, and memory manipulation.
  4. C18 (ISO/IEC 9899:2018) is the most recent standard and includes updates and clarifications to the language specification and the library.

When writing C code, it’s important to know which standard version is being used and to write code that is compatible with that standard. Many compilers support multiple standard versions, and it’s often possible to specify which version to use with a compiler flag or directive.

Here are some advantages and disadvantages of using the C programming language:

Advantages:

  1. Efficiency: C is a fast and efficient language that can be used to create high-performance applications.
  2. Portability: C programs can be compiled and run on a wide range of platforms and operating systems.
  3. Low-level access: C provides low-level access to system resources, making it ideal for systems programming and developing operating systems.
  4. Large user community: C has a large and active user community, which means there are many resources and libraries available for developers.
  5. Widely used: C is a widely used language, and many modern programming languages are built on top of it.

Disadvantages:

  1. Steep learning curve: C can be difficult to learn, especially for beginners, due to its complex syntax and low-level access to system resources.
  2. Lack of memory management: C does not provide automatic memory management, which can lead to memory leaks and other memory-related bugs if not handled properly.
  3. No built-in support for object-oriented programming: C does not provide built-in support for object-oriented programming, making it more difficult to write object-oriented code compared to languages like Java or Python.
  4. No built-in support for concurrency: C does not provide built-in support for concurrency, making it more difficult to write multithreaded applications compared to languages like Java or Go.
  5. Security vulnerabilities: C programs are prone to security vulnerabilities, such as buffer overflows, if not written carefully.
    Overall, C is a powerful language with many advantages, but it also requires a high degree of expertise to use effectively and has some potential drawbacks, especially for beginners or developers working on complex projects.

Importance:

important for several reasons:

  1. Choosing the right programming language: Knowing the advantages and disadvantages of C can help developers choose the right programming language for their projects. For example, if high performance is a priority, C may be a good choice, but if ease of use or built-in memory management is important, another language may be a better fit.
  2. Writing efficient code: Understanding the efficiency advantages of C can help developers write more efficient and optimized code, which is especially important for systems programming and other performance-critical applications.
  3. Avoiding common pitfalls: Understanding the potential disadvantages of C, such as memory management issues or security vulnerabilities, can help developers avoid common pitfalls and write safer, more secure code.
  4. Collaboration and communication: Knowing the advantages and disadvantages of C can also help developers communicate and collaborate effectively with others on their team or in the wider programming community.

The idea of this article is to introduce C standard. 

What to do when a C program produces different results in two different compilers? 
For example, consider the following simple C program. 

C

void main() {  }

The above program fails in GCC as the return type of main is void, but it compiles in Turbo C. How do we decide whether it is a legitimate C program or not? 

Consider the following program as another example. It produces different results in different compilers. 

C

// C++ Program to illustrate the difference in different
// compiler execution
#include <stdio.h>
int main()
{
    int i = 1;
    printf("%d %d %d\n", i++, i++, i);
    return 0;
}
2 1 3 - using g++ 4.2.1 on Linux.i686
1 2 3 - using SunStudio C++ 5.9 on Linux.i686
2 1 3 - using g++ 4.2.1 on SunOS.x86pc
1 2 3 - using SunStudio C++ 5.9 on SunOS.x86pc
1 2 3 - using g++ 4.2.1 on SunOS.sun4u
1 2 3 - using SunStudio C++ 5.9 on SunOS.sun4u

Source: Stackoverflow
Which compiler is right?
The answer to all such questions is C standard. In all such cases, we need to see what C standard says about such programs.

What is C standard? 
The latest C standard is ISO/IEC 9899:2018, also known as C17 as the final draft was published in 2018. Before C11, there was C99. The C11 final draft is available here. See this for a complete history of C standards.

Can we know the behavior of all programs from C standard? 
C standard leaves some behavior of many C constructs as undefined and some as unspecified to simplify the specification and allow some flexibility in implementation. For example, in C the use of any automatic variable before it has been initialized yields undefined behavior and order of evaluations of subexpressions is unspecified. This specifically frees the compiler to do whatever is easiest or most efficient, should such a program be submitted.

So what is the conclusion about above two examples? 
Let us consider the first example which is “void main() {}”, the standard says following about prototype of main().

The function called at program startup is named main. The implementation 
declares no prototype for this function. It shall be defined with a return
type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names
may be used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.

So the return type void doesn’t follow the standard, and it’s something allowed by certain compilers.

Let us talk about the second example. Note the following statement in C standard is listed under unspecified behavior.  

The order in which the function designator, arguments, and 
subexpressions within the arguments are evaluated in a function
call (6.5.2.2).

C Program to Print “Hello World”

The following C program displays “Hello World” in the output.

// Simple C program to display "Hello World"
 
// Header file for input output functions
#include <stdio.h>
 
// main function -
// where the execution of program begins
int main()
{
 
    // prints hello world
    printf("Hello World");
 
    return 0;
}
Output
Hello World

Compiling the First C Program

Before proceeding to write the first program, the user needs to set up a C program compiler, which would compile and execute the “Hello World” program. Here we have used a Windows-based GCC compiler to compile and run the program. To know more on how to set up the local GCC compiler or run using online ide refer to Setting C Development Environment.

Step 1:This requires writing the “Hello World” program, in a text editor and saving the file with the extension .c, for example, we have stored the program in a C-type file HelloWorld.c.

Step 2: This includes opening CMD or command prompt line and navigating to the directory where the file HelloWorld.c is present. Here it is present in C:\Users\Chin\Sample.

Step 3: To compile the code execute the following command:

gcc HelloWorld.c

This would create a C-executable file with a random name given by the compiler itself. We got the executable filename as a.

To give a user-oriented name, run the following command:

gcc -o helloworld HelloWorld.c/pre>

This would create a C-executable file by the name helloworld.

Step 4: To run the executable file to get the result, run the following command:

helloworld

Explanation of the Code

Let us now understand the terminologies of the above program:

Line 1:

// Simple C program to display “Hello World”
  1. This is a single comment line. A comment is used to display additional information about the program.
  2. A comment does not contain any programming logic as it is not read by the compiler. When a comment is encountered by a compiler, the compiler simply skips that line of code.
  3. Any line beginning with ‘//’ without quotes OR in between /*…*/ in C is a comment.

More on Comments in C

Line 3:

#include 
  1. In C,  all lines that start with the pound (#) sign are called directives. These statements are processed by preprocessor program invoked by the compiler.
  2. The #include directive tells the compiler to include a file and #include<stdio.h> tells the compiler to include the header file for the Standard Input Output file which contains declarations of all the standard input/output library functions.

More on Preprocessors in C.

Line 6:

int main()
  1. This line is used to declare a function named “main” which returns data of integer type. A function is a group of statements that are designed to perform a specific task. Execution of every C program begins with the main() function, no matter where the function is located in the program. So, every C program must have a main() function and this is the function where the execution of the program begins.
  2. { and }: The opening braces ‘{‘ indicates the beginning of the main function and the closing braces ‘}’ indicates the ending of the main function. Everything between these two comprises the body of the main function and are called the blocks.

More on main() function in C.

Line 10:

printf("Hello World");
  1. This line tells the compiler to display the message “Hello World” on the screen. This line is called a statement in C. Every statement is meant to perform some task. A semi-colon ‘;’ is used to end a statement. The semi-colon character at the end of the statement is used to indicate that the statement is ending there.
  2. The printf() function is used to print a character stream of data on the stdout console. Everything within ” ” is displayed on the output device.

More on Input/Output in C.

Line 12:

return 0;
  1. This is also a statement. This statement is used to return a value from a function and indicates the finishing of a function. This statement is basically used in functions to return the results of the operations performed by a function.
  2. Indentation: As you can see the printf and the return statement have been indented or moved to the right side. This is done to make the code more readable. In a program as Hello World, it does not seem to hold much relevance but as the program becomes more complex, it makes the code more readable and less error-prone. Therefore, one must always use indentations and comments to make the code more readable.

The comments in C are human-readable explanations or notes in the source code of a C program.  A comment makes the program easier to read and understand. These are the statements that are not executed by the compiler or an interpreter.

It is considered to be a good practice to document our code using comments.

When and Why to use Comments in C programming?

  1. A person reading a large code will be bemused if comments are not provided about details of the program.
  2. C Comments are a way to make a code more readable by providing more descriptions.
  3. C Comments can include a description of an algorithm to make code understandable.
  4. C Comments can be used to prevent the execution of some parts of the code.

Types of comments in C

In C there are two types of comments in C language:

  • Single-line comment
  • Multi-line comment
comments in c

Types of Comments in C

1. Single-line Comment in C

A single-line comment in C starts with ( // ) double forward slash. It extends till the end of the line and we don’t need to specify its end.

Syntax of Single Line C Comment

// This is a single line comment

Example 1: C Program to illustrate single-line comment

C

// C program to illustrate
// use of single-line comment
#include <stdio.h>
 
int main(void)
{
    // This is a single-line comment
    printf("Welcome to GeeksforGeeks");
    return 0;
}
Output: 
Welcome to GeeksforGeeks

 

Comment at End of Code Line

We can also create a comment that displays at the end of a line of code using a single-line comment. But generally, it’s better to practice putting the comment before the line of code.

Example: 

C

// C program to demonstrate commenting after line of code
#include <stdio.h>
 
int main() {
    // single line comment here
   
      printf("Welcome to GeeksforGeeks"); // comment here
    return 0;
}
Output
Welcome to GeeksforGeeks

2. Multi-line Comment in C

The Multi-line comment in C starts with a forward slash and asterisk ( /* ) and ends with an asterisk and forward slash ( */ ). Any text between /* and */ is treated as a comment and is ignored by the compiler.

It can apply comments to multiple lines in the program.

Syntax of Multi-Line C Comment

/*Comment starts
    continues
    continues
    .
    .
    .
Comment ends*/

Example 2:  C Program to illustrate the multi-line comment

C

/* C program to illustrate
use of
multi-line comment */
#include <stdio.h>
int main(void)
{
    /*
    This is a
    multi-line comment
    */
   
      /*
    This comment contains some code which
    will not be executed.
    printf("Code enclosed in Comment");
    */
    printf("Welcome to GeeksforGeeks");
    return 0;
}
Output: 
Welcome to GeeksforGeeks

variable in C language is the name associated with some memory location to store data of different types. There are many types of variables in C depending on the scope, storage class, lifetime, type of data they store, etc. A variable is the basic building block of a C program that can be used in expressions as a substitute in place of the value it stores.

What is a variable in C?

variable in C is a memory location with some name that helps store some form of data and retrieves it when required. We can store different types of data in the variable and reuse the same variable for storing some other data any number of times.

They can be viewed as the names given to the memory location so that we can refer to it without having to memorize the memory address. The size of the variable depends upon the data type it stores.

C Variable Syntax

The syntax to declare a variable in C specifies the name and the type of the variable.

data_type variable_name = value;    // defining single variable
            or
data_type variable_name1, variable_name2;    // defining multiple variable

Here,

  • data_type: Type of data that a variable can store.
  • variable_name: Name of the variable given by the user.
  • value: value assigned to the variable by the user.

Example

int var;    // integer variable
char a;     // character variable
float fff;  // float variables

Note: C is a strongly typed language so all the variables types must be specified before using them.

variable declaration breakdown

Variable Syntax Breakdown

There are 3 aspects of defining a variable:

  1. Variable Declaration
  2. Variable Definition
  3. Variable Initialization

1. C Variable Declaration

Variable declaration in C tells the compiler about the existence of the variable with the given name and data type. No memory is allocated to a variable in the declaration.

2. C Variable Definition

In the definition of a C variable, the compiler allocates some memory and some value to it. A defined variable will contain some random garbage value till it is not initialized.

Example

int var;
char var2;

Note: Most of the modern C compilers declare and define the variable in single step. Although we can declare a variable in C by using extern keyword, it is not required in most of the cases. To know more about variable declaration and definition, click here.

3. C Variable Initialization

Initialization of a variable is the process where the user assigns some meaningful value to the variable.

Example

int var; // variable definition
var = 10; // initialization
      or
int var = 10; // variable declaration and definition

How to use variables in C?

The below example demonstrates how the use variables in C language.

C

// C program to demonstrate the
// declaration, definition and
// initialization
#include <stdio.h>
 
int main()
{
    // declaration with definition
    int defined_var;
 
    printf("Defined_var: %d\n", defined_var);
 
    // initialization
    defined_var = 12;
 
    // declaration + definition + initialization
    int ini_var = 25;
 
    printf("Value of defined_var after initialization: %d\n",defined_var);
    printf("Value of ini_var: %d", ini_var);
 
    return 0;
}
Output
Defined_var: 0
Value of defined_var after initialization: 12
Value of ini_var: 25

Rules for Naming Variables in C

You can assign any name to the variable as long as it follows the following rules:

  1. A variable name must only contain alphabets, digits, and underscore.
  2. A variable name must start with an alphabet or an underscore only. It cannot start with a digit.
  3. No whitespace is allowed within the variable name.
  4. A variable name must not be any reserved word or keyword.
variable names examples

 

C Variable Types

The C variables can be classified into the following types:

  1. Local Variables
  2. Global Variables
  3. Static Variables
  4. Automatic Variables
  5. Extern Variables
  6. Register Variables

1. Local Variables in C

Local variable in C is a variable that is declared inside a function or a block of code. Its scope is limited to the block or function in which it is declared.

Example of Local Variable in C

C

// C program to declare and print local variable inside a
// function.
#include <stdio.h>
 
void function()
{
    int x = 10; // local variable
    printf("%d", x);
}
 
int main() { function(); }
Output
10

In the above code, x can be used only in the scope of function(). Using it in the main function will give an error.

2. Global Variables in C

Global variable in C is a variable that is declared outside the function or a block of code. Its scope is the whole program i.e. we can access the global variable anywhere in the C program after it is declared.

Example of Global Variable in C

C

// C program to demonstrate use of global variable
#include <stdio.h>
 
int x = 20; // global variable
 
void function1() { printf("Function 1: %d\n", x); }
 
void function2() { printf("Function 2: %d\n", x); }
 
int main()
{
 
    function1();
    function2();
    return 0;
}
Output
Function 1: 20
Function 2: 20

In the above code, both functions can use the global variable as global variables are accessible by all the functions.

Note: When we have same name for local and global variable, local variable will be given preference over the global variable by the compiler.

For accessing global variable in this case, we can use the method mention here.

3. Static Variables in C

static variable in C is a variable that is defined using the static keyword. It can be defined only once in a C program and its scope depends upon the region where it is declared (can be global or local).

The default value of static variables is zero.

Syntax of Static Variable in C

static data_type variable_name = initial_value;

As its lifetime is till the end of the program, it can retain its value for multiple function calls as shown in the example.

Example of Static Variable in C

C

// C program to demonstrate use of static variable
#include <stdio.h>
 
void function()
{
    int x = 20; // local variable
    static int y = 30; // static variable
    x = x + 10;
    y = y + 10;
    printf("\tLocal: %d\n\tStatic: %d\n", x, y);
}
 
int main()
{
    printf("First Call\n");
    function();
    printf("Second Call\n");
    function();
    printf("Third Call\n");
    function();
    return 0;
}
Output
First Call
    Local: 30
    Static: 40
Second Call
    Local: 30
    Static: 50
Third Call
    Local: 30
    Static: 60

In the above example, we can see that the local variable will always print the same value whenever the function will be called whereas the static variable will print the incremented value in each function call.

Note: Storage Classes in C is the concept that helps us to determine the scope, lifetime, memory location, and default value (initial value) of a variable.

4. Automatic Variable in C

All the local variables are automatic variables by default. They are also known as auto variables.

Their scope is local and their lifetime is till the end of the block. If we need, we can use the auto keyword to define the auto variables.

The default value of the auto variables is a garbage value.

Syntax of Auto Variable in C

auto data_type variable_name;
        or
data_type variable_name;    (in local scope)

Example of auto Variable in C

C

// C program to demonstrate use of automatic variable
#include <stdio.h>
 
void function()
{
    int x = 10; // local variable (also automatic)
    auto int y = 20; // automatic variable
    printf("Auto Variable: %d", y);
}
int main()
{
 
    function();
    return 0;
}
Output
Auto Variable: 20

In the above example, both x and y are automatic variables. The only difference is that variable y is explicitly declared with the auto keyword.

5. External Variables in C

External variables in C can be shared between multiple C files. We can declare an external variable using the extern keyword.

Their scope is global and they exist between multiple C files.

Syntax of Extern Variables in C

extern data_type variable_name;

Example of Extern Variable in C

  ----------myfile.h------------
  extern int x=10;  //external variable (also global)

   
  ----------program1.c----------
  #include "myfile.h"
  #include <stdio.h>
  void printValue(){
  printf("Global variable: %d", x);
  }

In the above example, x is an external variable that is used in multiple C files.

6. Register Variables in C

Register variables in C are those variables that are stored in the CPU register instead of the conventional storage place like RAM. Their scope is local and exists till the end of the block or a function.

These variables are declared using the register keyword.

The default value of register variables is a garbage value.

Syntax of Register Variables in C

register data_type variable_name = initial_value;

Example of Register Variables in C

C

// C program to demonstrate the definition of register
// variable
#include <stdio.h>
 
int main()
{
    //    register variable
    register int var = 22;
 
    printf("Value of Register Variable: %d\n", var);
    return 0;
}
Output
Value of Register Variable: 22

NOTE: We cannot get the address of the register variable using addressof (&) operator because they are stored in the CPU register. The compiler will throw an error if we try to get the address of register variable.

Constant Variable in C

Till now we have only seen the variables whose values can be modified any number of times. But C language also provides us a way to make the value of a variable immutable. We can do that by defining the variable as constant.

constant variable in C is a read-only variable whose value cannot be modified once it is defined. We can declare a constant variable using the const keyword.

Syntax of Const Variable in C

const data_type variable_name = value;

Note: We have to always initialize the const variable at the definition as we cannot modify its value after defining.

Example of Const Variable in C

C

// C Program to Demonstrate constant variable
#include <stdio.h>
 
int main()
{
    // variable
    int not_constant;
 
    // constant variable;
    const int constant = 20;
 
    // changing values
    not_constant = 40;
    constant = 22;
 
    return 0;
}

Output

constant variable program output

 

The constants in C are the read-only variables whose values cannot be modified once they are declared in the C program. The type of constant can be an integer constant, a floating pointer constant, a string constant, or a character constant. In C language, the const keyword is used to define the constants.

What is a constant in C?

As the name suggests, a constant in C is a variable that cannot be modified once it is declared in the program. We can not make any change in the value of the constant variables after they are defined.

How to define a constant in C?

We define a constant in C language using the const keyword. Also known as a const type qualifier, the const keyword is placed at the start of the variable declaration to declare that variable as a constant.

Syntax to Define Constant

const data_type var_name = value;
syntax of constants in c

 

Example of Constants in C

C

// C program to illustrate constant variable definition
#include <stdio.h>
 
int main()
{
 
    // defining integer constant using const keyword
    const int int_const = 25;
 
    // defining character constant using const keyword
    const char char_const = 'A';
 
    // defining float constant using const keyword
    const float float_const = 15.66;
 
    printf("Printing value of Integer Constant: %d\n",
           int_const);
    printf("Printing value of Character Constant: %c\n",
           char_const);
    printf("Printing value of Float Constant: %f",
           float_const);
 
    return 0;
}
Output
Printing value of Integer Constant: 25
Printing value of Character Constant: A
Printing value of Float Constant: 15.660000

One thing to note here is that we have to initialize the constant variables at declaration. Otherwise, the variable will store some garbage value and we won’t be able to change it. The following image describes examples of incorrect and correct variable definitions.

right way to declare constants in c

 

Types of Constants in C

The type of the constant is the same as the data type of the variables. Following is the list of the types of constants

  • Integer Constant
  • Character Constant
  • Floating Point Constant
  • Double Precision Floating Point Constant
  • Array Constant
  • Structure Constant

We just have to add the const keyword at the start of the variable declaration.

Properties of Constant in C

The important properties of constant variables in C defined using the const keyword are as follows:

1. Initialization with Declaration

We can only initialize the constant variable in C at the time of its declaration. Otherwise, it will store the garbage value.

2. Immutability

The constant variables in c are immutable after its definition, i.e., they can be initialized only once in the whole program. After that, we cannot modify the value stored inside that variable.

C

// C Program to demonstrate the behaviour of constant
// variable
#include <stdio.h>
 
int main()
{
    // declaring a constant variable
    const int var;
    // initializing constant variable var after declaration
    var = 20;
 
    printf("Value of var: %d", var);
    return 0;
}

Output

In function 'main':
10:9: error: assignment of read-only variable 'var'
10 |     var = 20;
   |         ^

Difference between Constants and Literals

The constant and literals are often confused as the same. But in C language, they are different entities and have different semantics. The following table list the differences between the constants and literals in C:

Constant

Literals

Constants are variables that cannot be modified once declared.Literals are the fixed values that define themselves.
Constants are defined by using the const keyword in C. They store literal values in themselves.They themselves are the values that are assigned to the variables or constants.
We can determine the address of constants.We cannot determine the address of a literal except string literal.
They are lvalues.They are rvalues.
Example: const int c = 20.Example: 24,15.5, ‘a’, “Geeks”, etc.

Defining Constant using #define Preprocessor

We can also define a constant in C using #define preprocessor. The constant defined using #define are macros that behaves like a constant. These constants are not handled by the compiler, they are handled by the preprocessor and are replaced by their value before complication.

Syntax of Constant in C using #define

#define const_name value

Example

C

// C Program to define a constant using #define
#include <stdio.h>
#define pi 3.14
 
int main()
{
 
    printf("The value of pi: %.2f", pi);
    return 0;
}
Output
The value of pi: 3.14

FAQs on C Constants

1. Define C Constants.

Constants in C are the immutable variables whose values cannot be modified once they are declared in the C program.

2. What is the use of the const keyword?

The const keyword is the qualifier that is used to declare the constant variable in C language.

3. Can we initialize the constant variable after the declaration?

No, we cannot initialize the constant variable once it is declared.

4. What is the right way to declare the constant in C?

The right way to declare a constant in C is to always initialize the constant variable when we declare.

5. What is the difference between constant defined using const qualifier and #define?

The following table list the differences between the constants defined using const qualifier and #define in C:

Constants using constConstants using #define
They are the variables that are immutableThey are the macros that are replaced by their value.
They are handled by the compiler.They are handled by the preprocessor.
Syntax: const type name = value;Syntax: #define name value

6. Is there any way to change the value of a constant variable in C?

Yes, we can take advantage of the loophole created by pointers to change the value of a variable declared as a constant in C. The below C program demonstrates how to do it.

C

// C Program to change the value of constant variable
#include <stdio.h>
 
int main()
{
 
    // defining an integer constant
    const int var = 10;
 
    printf("Initial Value of Constant: %d\n", var);
 
    // defining a pointer to that const variable
    int* ptr = &var;
    // changing value
    *ptr = 500;
    printf("Final Value of Constant: %d", var);
    return 0;
}
Output
Initial Value of Constant: 10
Final Value of Constant: 500

The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed (which depends upon where const variables are stored, we may change the value of the const variable by using a pointer). The result is implementation-defined if an attempt is made to change a const.

Using the const qualifier in C is a good practice when we want to ensure that some values should remain constant and should not be accidentally modified.

In C programming, the const qualifier can be used in different contexts to provide various behaviors. Here are some different use cases of the const qualifier in C:

1. Constant Variables

const int var = 100;

In this case, const is used to declare a variable var as a constant with an initial value of 100. The value of this variable cannot be modified once it is initialized. See the following example:

// C program to demonstrate that constant variables can not
// be modified
#include <stdio.h>
 
int main()
{
    const int var = 100;
 
    // Compilation error: assignment of read-only variable
    // 'var'
    var = 200;
 
    return 0;
}

Output

./Solution.cpp: In function 'int main()':
./Solution.cpp:11:9: error: assignment of read-only variable 'var'
     var = 200;
         ^

2. Pointer to Constant

const int* ptr;

OR

int const *ptr;

We can change the pointer to point to any other integer variable, but cannot change the value of the object (entity) pointed using pointer ptr. The pointer is stored in the read-write area (stack in the present case). The object pointed may be in the read-only or read-write area. Let us see the following examples.

Example 1:

// C program to demonstrate that  the pointer to point to
// any other integer variable, but the value of the object
// (entity) pointed can not be changed
 
#include <stdio.h>
int main(void)
{
    int i = 10;
    int j = 20;
    /* ptr is pointer to constant */
    const int* ptr = &i;
 
    printf("ptr: %d\n", *ptr);
    /* error: object pointed cannot be modified
    using the pointer ptr */
    *ptr = 100;
 
    ptr = &j; /* valid */
    printf("ptr: %d\n", *ptr);
 
    return 0;
}

Output

./Solution.c: In function 'main':
./Solution.c:12:10: error: assignment of read-only location '*ptr'
     *ptr = 100;
          ^

Example 2: Program where variable i itself is constant.

// C program to demonstrate that  the pointer to point to
// any other integer variable, but the value of the object
// (entity) pointed can not be changed
 
#include <stdio.h>
 
int main(void)
{
    /* i is stored in read only area*/
    int const i = 10;
    int j = 20;
 
    /* pointer to integer constant. Here i
    is of type "const int", and &i is of
    type "const int *".  And p is of type
    "const int", types are matching no issue */
    int const* ptr = &i;
 
    printf("ptr: %d\n", *ptr);
 
    /* error */
    *ptr = 100;
 
    /* valid. We call it up qualification. In
    C/C++, the type of "int *" is allowed to up
    qualify to the type "const int *". The type of
    &j is "int *" and is implicitly up qualified by
    the compiler to "const int *" */
 
    ptr = &j;
    printf("ptr: %d\n", *ptr);
 
    return 0;
}

Output

./Solution.c: In function 'main':
./Solution.c:18:10: error: assignment of read-only location '*ptr'
     *ptr = 100;
          ^

Down qualification is not allowed in C++ and may cause warnings in C. Down qualification refers to the situation where a qualified type is assigned to a non-qualified type.

Example 3: Program to show down qualification.

// C program to demonstrate the down qualification
 
#include <stdio.h>
 
int main(void)
{
    int i = 10;
    int const j = 20;
 
    /* ptr is pointing an integer object */
    int* ptr = &i;
 
    printf("*ptr: %d\n", *ptr);
 
    /* The below assignment is invalid in C++, results in
       error In C, the compiler *may* throw a warning, but
       casting is implicitly allowed */
    ptr = &j;
 
    /* In C++, it is called 'down qualification'. The type
       of expression &j is "const int *" and the type of ptr
       is "int *". The assignment "ptr = &j" causes to
       implicitly remove const-ness from the expression &j.
       C++ being more type restrictive, will not allow
       implicit down qualification. However, C++ allows
       implicit up qualification. The reason being, const
       qualified identifiers are bound to be placed in
       read-only memory (but not always). If C++ allows
       above kind of assignment (ptr = &j), we can use 'ptr'
       to modify value of j which is in read-only memory.
       The consequences are implementation dependent, the
       program may fail
       at runtime. So strict type checking helps clean code.
     */
 
    printf("*ptr: %d\n", *ptr);
 
    return 0;
}

Output

main.c: In function ‘main’:
main.c:16:9: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
   16 |     ptr = &j;
      |         ^
*ptr: 10
*ptr: 20

3. Constant Pointer to Variable

int* const ptr;

The above declaration is a constant pointer to an integer variable, which means we can change the value of the object pointed by the pointer, but cannot change the pointer to point to another variable.

Example

// C program to demonstrate that the value of object pointed
// by pointer can be changed but the pointer can not point
// to another variable
 
#include <stdio.h>
 
int main(void)
{
    int i = 10;
    int j = 20;
    /* constant pointer to integer */
    int* const ptr = &i;
 
    printf("ptr: %d\n", *ptr);
 
    *ptr = 100; /* valid */
    printf("ptr: %d\n", *ptr);
 
    ptr = &j; /* error */
    return 0;
}

Output

./Solution.c: In function 'main':
./Solution.c:15:9: error: assignment of read-only variable 'ptr'
     ptr = &j; /* error */
         ^

4. Constant Pointer to Constant

const int* const ptr;

The above declaration is a constant pointer to a constant variable which means we cannot change the value pointed by the pointer as well as we cannot point the pointer to other variables. Let us see with an example. 

// C program to demonstrate that value pointed by the
// pointer can not be changed as well as we cannot point the
// pointer to other variables
 
#include <stdio.h>
 
int main(void)
{
    int i = 10;
    int j = 20;
    /* constant pointer to constant integer */
    const int* const ptr = &i;
 
    printf("ptr: %d\n", *ptr);
 
    ptr = &j; /* error */
    *ptr = 100; /* error */
 
    return 0;
}

Output

./Solution.c: In function 'main':
./Solution.c:12:9: error: assignment of read-only variable 'ptr'
     ptr = &j; /* error */
         ^
./Solution.c:13:10: error: assignment of read-only location '*ptr'
     *ptr = 100; /* error */
          ^

Advantages of const Qualifiers in C

The const qualifier in C has the following advantages:

  • Improved Code Readability: By marking a variable as const, you indicate to other programmers that its value should not be changed, making your code easier to understand and maintain.
  • Enhanced Type Safety: By using const, you can ensure that values are not accidentally modified, reducing the chance of bugs and errors in your code.
  • Improved Optimization: Compilers can optimize const variables more effectively, as they know that their values will not change during program execution. This can result in faster and more efficient code.
  • Better Memory Usage: By declaring variables as const, you can often avoid having to make a copy of their values, which can reduce memory usage and improve performance.
  • Improved Compatibility: By declaring variables as const, you can make your code more compatible with other libraries and APIs that use const variables.
  • Improved Reliability: By using const, you can make your code more reliable, as you can ensure that values are not modified unexpectedly, reducing the risk of bugs and errors in your code.

Summary

TypeDeclarationPointer Value Change
(*ptr = 100)
Pointing Value Change
(ptr  = &a)
Pointer to Variableint * ptrYesYes
Pointer to Constantconst int * ptr
int const * ptr
NoYes
Constant Pointer to Variableint * const ptrYesNo
Constant Pointer to Constantconst int * const ptrNoNo
  There are many different ways to make the variable as constant
  1. Using const keyword: The const keyword specifies that a variable or object value is constant and can’t be modified at the compilation time.

    // C program to demonstrate const specifier
    #include <stdio.h>
    int main()
    {
        const int num = 1;
      
        num = 5; // Modifying the value
        return 0;
    }
    It will throw as error like:
    error: assignment of read-only variable ‘num’
    
  2. Using enum keyword: Enumeration (or enum) is a user defined data type in C and C++. It is mainly used to assign names to integral constants, that make a program easy to read and maintain.

    // In C and C++ internally the default
    // type of 'var' is int
    enum VARS { var = 42 };
      
    // In C++ 11 (can have any integral type):
    enum : type { var = 42; }
      
    // where mytype = int, char, long etc.
    // but it can't be float, double or
    // user defined data type.

    Note: The data types of enum are of course limited as we can see in above example.

  3. Using constexpr keyword: Using constexpr in C++(not in C) can be used to declare variable as a guaranteed constant. But it would fail to compile if its initializer isn’t a constant expression.

    #include <iostream>
      
    int main()
    {
        int var = 5;
        constexpr int k = var;
        std::cout << k;
        return 0;
    }

    Above program will throw an error i.e.,

    error: the value of ‘var’ is not usable in a constant expression

    because the variable ‘var’ in not constant expression. Hence in order to make it as constant, we have to declare the variable ‘var’ with const keyword.

  4. Using Macros: We can also use Macros to define constant, but there is a catch,
    #define var 5

Since Macros are handled by the pre-processor(the pre-processor does text replacement in our source file, replacing all occurrences of ‘var’ with the literal 5) not by the compiler.
Hence it wouldn’t be recommended because Macros doesn’t carry type checking information and also prone to error. In fact not quite constant as ‘var’ can be redefined like this,

Output:
5 10

Internal Linkage and External Linkage in C

It is often quite hard to distinguish between scope and linkage, and the roles they play. This article focuses on scope and linkage, and how they are used in C language.
Note: All C programs have been compiled on 64 bit GCC 4.9.2. Also, the terms “identifier” and “name” have been used interchangeably in this article.


Definitions

  • Scope : Scope of an identifier is the part of the program where the identifier may directly be accessible. In C, all identifiers are lexically (or statically) scoped.
  • Linkage : Linkage describes how names can or can not refer to the same entity throughout the whole program or one single translation unit.
    The above sounds similar to Scope, but it is not so. To understand what the above means, let us dig deeper into the compilation process.
  • Translation Unit : A translation unit is a file containing source code, header files and other dependencies. All of these sources are grouped together to form a single translation unit which can then be used by the compiler to produce one single executable object. It is important to link the sources together in a meaningful way. For example, the compiler should know that printf definition lies in stdio header file.

In C and C++, a program that consists of multiple source code files is compiled one at a time. Until the compilation process, a variable can be described by it’s scope. It is only when the linking process starts, that linkage property comes into play. Thus, scope is a property handled by compiler, whereas linkage is a property handled by linker.

The Linker links the resources together in the linking stage of compilation process. The Linker is a program that takes multiple machine code files as input, and produces an executable object code. It resolves symbols (i.e, fetches definition of symbols such as “+” etc..) and arranges objects in address space.

Linkage is a property that describes how variables should be linked by the linker. Should a variable be available for another file to use? Should a variable be used only in the file declared? Both are decided by linkage.
Linkage thus allows you to couple names together on a per file basis, scope determines visibility of those names.
There are 2 types of linkage:

  1. Internal Linkage: An identifier implementing internal linkage is not accessible outside the translation unit it is declared in. Any identifier within the unit can access an identifier having internal linkage. It is implemented by the keyword static. An internally linked identifier is stored in initialized or uninitialized segment of RAM. (note: static also has a meaning in reference to scope, but that is not discussed here).
    Some Examples:

    Animals.cpp

    // C code to illustrate Internal Linkage
    #include <stdio.h>
      
    static int animals = 8;
    const int i = 5;
      
    int call_me(void)
    {
        printf("%d %d", i, animals);
    }

    The above code implements static linkage on identifier animals. Consider Feed.cpp is located in the same translation unit.

    Feed.cpp

    // C code to illustrate Internal Linkage
    #include <stdio.h>
      
    int main()
    {
        call_me();
        animals = 2;
        printf("%d", animals);
        return 0;
    }

    On compiling Animals.cpp first and then Feed.cpp, we get

    Output : 5 8 2
    

    Now, consider that Feed.cpp is located in a different translation unit. It will compile and run as above only if we use #include "Animals.cpp".
    Consider Wash.cpp located in a 3rd translation unit.

    Wash.cpp

    // C code to illustrate Internal Linkage
    #include <stdio.h>
    #include "animal.cpp" // note that animal is included.
      
    int main()
    {
        call_me();
        printf("\n having fun washing!");
        animals = 10;
        printf("%d\n", animals);
        return 0;
    }

    On compiling, we get:

    Output : 5 8
    having fun washing!
    10
    

    There are 3 translation units (Animals, Feed, Wash) which are using animals code.
    This leads us to conclude that each translation unit accesses it’s own copy of animals. That is why we have animals = 8 for Animals.cppanimals = 2 for Feed.cpp and animals = 10 for Wash.cpp. A file. This behavior eats up memory and decreases performance.

    Another property of internal linkage is that it is only implemented when the variable has global scope, and all constants are by default internally linked.

    Usage : As we know, an internally linked variable is passed by copy. Thus, if a header file has a function fun1() and the source code in which it is included in also has fun1() but with a different definition, then the 2 functions will not clash with each other. Thus, we commonly use internal linkage to hide translation-unit-local helper functions from the global scope. For example, we might include a header file that contains a method to read input from the user, in a file that may describe another method to read input from the user. Both of these functions are independent of each other when linked.

  2. External Linkage: An identifier implementing external linkage is visible to every translation unit. Externally linked identifiers are shared between translation units and are considered to be located at the outermost level of the program. In practice, this means that you must define an identifier in a place which is visible to all, such that it has only one visible definition. It is the default linkage for globally scoped variables and functions. Thus, all instances of a particular identifier with external linkage refer to the same identifier in the program. The keyword extern implements external linkage.

    When we use the keyword extern, we tell the linker to look for the definition elsewhere. Thus, the declaration of an externally linked identifier does not take up any space. Extern identifiers are generally stored in initialized/uninitialized or text segment of RAM.

    Please do go through Understanding extern keyword in C before proceeding to the following examples.
    It is possible to use an extern variable in a local scope. This shall further outline the differences between linkage and scope. Consider the following code:

    // C code to illustrate External Linkage
    #include <stdio.h>
      
    void foo()
    {
        int a;
        extern int b; // line 1
    }
      
    void bar()
    {
        int c;
        c = b; // error
    }
      
    int main()
    {
        foo();
        bar();
    }
    Error: 'b' was not declared in this scope
    


    Explanation :
     The variable b has local scope in the function foo, even though it is an extern variable. Note that compilation takes place before linking; i.e scope is a concept that can be used only during compile phase. After the program is compiled there is no such concept as “scope of variable”.

    During compilation, scope of b is considered. It has local scope in foo(). When the compiler sees the extern declaration, it trusts that there is a definition of b somewhere and lets the linker handle the rest.

    However, the same compiler will go through the bar() function and try to find variable b. Since b has been declared extern, it has not been given memory yet by the compiler; it does not exist yet. The compiler will let the linker find the definition of b in the translation unit, and then the linker will assign b the value specified in definition. It is only then that b will exist and be assigned memory. However, since there is no declaration given at compile time within the scope of bar(), or even in global scope, the compiler complains with the error above.

    Given that it is the compiler’s job to make sure that all variables are used within their scopes, it complains when it sees b in bar(), when b has been declared in foo()‘s scope. The compiler will stop compiling and the program will not be passed to the linker.

    We can fix the program by declaring b as a global variable, by moving line 1 to before foo‘s definition.

    Let us look at another example

    // C code to illustrate External Linkage
    #include <stdio.h>
      
    int x = 10;
    int z = 5;
      
    int main()
    {
      
        extern int y; // line 2
        extern int z;
        printf("%d %d %d", x, y, z);
    }
      
    int y = 2;
    Output: 10 2 5

Data Types in C

Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning as well as its characteristics.

The data types in C can be classified as follows:

Types

Description

Primitive Data TypesPrimitive data types are the most basic data types that are used for representing simple values such as integers, float, characters, etc.
User Defined Data TypesThe user-defined data types are defined by the user himself.
Derived TypesThe data types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types.
Data Types in C

 

Different data types also have different ranges up to which they can store numbers. These ranges may vary from compiler to compiler. Below is a list of ranges along with the memory requirement and format specifiers on the 32-bit GCC compiler.

Data Type 
 
Size (bytes) 
 
Range
 
Format Specifier 
 
short int 
 

 
-32,768 to 32,767 
 
%hd 
 
unsigned short int 
 

 
0 to 65,535 
 
%hu 
 
unsigned int 
 

 
0 to 4,294,967,295 
 
%u 
 
int 
 

 
-2,147,483,648 to 2,147,483,647 
 
%d 
 
long int 
 

 
-2,147,483,648 to 2,147,483,647 
 
%ld 
 
unsigned long int 
 

 
0 to 4,294,967,295 
 
%lu 
 
long long int 
 

 
-(2^63) to (2^63)-1 
 
%lld 
 
unsigned long long int 
 

 
0 to 18,446,744,073,709,551,615 
 
%llu 
 
signed char 
 

 
-128 to 127 
 
%c 
 
unsigned char 
 

 
0 to 255 
 
%c 
 
float 
 

 
1.2E-38 to 3.4E+38%f 
 
double 
 

 
1.7E-308 to 1.7E+308%lf 
 
long double 
 
16 
 
3.4E-4932 to 1.1E+4932%Lf 
 

Note: The long, short, signed and unsigned are datatype modifier that can be used with some primitive data types to change the size or length of the datatype.

The following are some main primitive data types in C:

Integer Data Type

The integer datatype in C is used to store the whole numbers without decimal values. Octal values, hexadecimal values, and decimal values can be stored in int data type in C. 

  • Range:  -2,147,483,648 to 2,147,483,647
  • Size: 4 bytes
  • Format Specifier: %d

Syntax of Integer

We use int keyword to declare the integer variable:

int var_name;

The integer data type can also be used as

  1. unsigned int: Unsigned int data type in C is used to store the data values from zero to positive numbers but it can’t store negative values like signed int.
  2. short int: It is lesser in size than the int by 2 bytes so can only store values from –32,768 to 32,767.
  3. long int: Larger version of the int datatype so can store values greater than int.
  4. unsigned short int: Similar in relationship with short int as unsigned int with int.

Note: The size of an integer data type is compiler-dependent. We can use sizeof operator to check the actual size of any data type.

Example of int

C

// C program to print Integer data types.
#include <stdio.h>
 
int main()
{
    // Integer value with positive data.
    int a = 9;
 
    // integer value with negative data.
    int b = -9;
 
    // U or u is Used for Unsigned int in C.
    int c = 89U;
 
    // L or l is used for long int in C.
    long int d = 99998L;
 
    printf("Integer value with positive data: %d\n", a);
    printf("Integer value with negative data: %d\n", b);
    printf("Integer value with an unsigned int data: %u\n",
           c);
    printf("Integer value with an long int data: %ld", d);
 
    return 0;
}
Output
Integer value with positive data: 9
Integer value with negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998

Character Data Type

Character data type allows its variable to store only a single character. The size of the character is 1 byte. It is the most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers.

  • Range: (-128 to 127) or (0 to 255)
  • Size: 1 byte
  • Format Specifier: %c

Syntax of char

The char keyword is used to declare the variable of character type:

char var_name;

Example of char

C

// C program to print Integer data types.
#include <stdio.h>
 
int main()
{
    char a = 'a';
    char c;
 
    printf("Value of a: %c\n", a);
 
    a++;
    printf("Value of a after increment is: %c\n", a);
 
    // c is assigned ASCII values
    // which corresponds to the
    // character 'c'
    // a-->97 b-->98 c-->99
    // here c will be printed
    c = 99;
 
    printf("Value of c: %c", c);
 
    return 0;
}
Output
Value of a: a
Value of a after increment is: b
Value of c: c

Float Data Type

In C programming float data type is used to store floating-point values. Float in C is used to store decimal and exponential values. It is used to store decimal numbers (numbers with floating point values) with single precision.

  • Range: 1.2E-38 to 3.4E+38
  • Size: 4 bytes
  • Format Specifier: %f

Syntax of float

The float keyword is used to declare the variable as a floating point:

float var_name;

Example of Float

C

// C Program to demonstrate use
// of Floating types
#include <stdio.h>
 
int main()
{
    float a = 9.0f;
    float b = 2.5f;
 
    // 2x10^-4
    float c = 2E-4f;
    printf("%f\n", a);
    printf("%f\n", b);
    printf("%f", c);
 
    return 0;
}
Output
9.000000
2.500000
0.000200

Double Data Type

Double data type in C is used to store decimal numbers (numbers with floating point values) with double precision. It is used to define numeric values which hold numbers with decimal values in C.

The double data type is basically a precision sort of data type that is capable of holding 64 bits of decimal numbers or floating points. Since double has more precision as compared to that float then it is much more obvious that it occupies twice the memory occupied by the floating-point type. It can easily accommodate about 16 to 17 digits after or before a decimal point.

  • Range: 1.7E-308 to 1.7E+308
  • Size: 8 bytes
  • Format Specifier: %lf

Syntax of Double

The variable can be declared as double precision floating point using the double keyword:

double var_name;

Example of Double

C

// C Program to demonstrate
// use of double data type
#include <stdio.h>
 
int main()
{
    double a = 123123123.00;
    double b = 12.293123;
    double c = 2312312312.123123;
 
    printf("%lf\n", a);
 
    printf("%lf\n", b);
 
    printf("%lf", c);
 
    return 0;
}
Output
123123123.000000
12.293123
2312312312.123123

Void Data Type

The void data type in C is used to specify that no value is present. It does not provide a result value to its caller. It has no values and no operations. It is used to represent nothing. Void is used in multiple ways as function return type, function arguments as void, and pointers to void.

Syntax:

// function return type void

void exit(int check);

// Function without any parameter can accept void.

int print(void);

// memory allocation function which
// returns a pointer to void.
void *malloc (size_t size);

Example of Void

C

// C program to demonstrate
// use of void pointers
#include <stdio.h>
 
int main()
{
    int val = 30;
    void* ptr = &val;
    printf("%d", *(int*)ptr);
    return 0;
}
Output
30

Size of Data Types in C

The size of the data types in C is dependent on the size of the architecture, so we cannot define the universal size of the data types. For that, the C language provides the sizeof() operator to check the size of the data types.

Example

C

// C Program to print size of
// different data type in C
#include <stdio.h>
 
int main()
{
    int size_of_int = sizeof(int);
    int size_of_char = sizeof(char);
    int size_of_float = sizeof(float);
    int size_of_double = sizeof(double);
 
    printf("The size of int data type : %d\n", size_of_int);
    printf("The size of char data type : %d\n",
           size_of_char);
    printf("The size of float data type : %d\n",
           size_of_float);
    printf("The size of double data type : %d",
           size_of_double);
 
    return 0;
}
Output
The size of int data type : 4
The size of char data type : 1
The size of float data type : 4
The size of double data type : 8

Literals in C/C++ With Examples

Literals are the Constant values that are assigned to the constant variables. Literals represent fixed values that cannot be modified. Literals contain memory but they do not have references as variables. Generally, both terms, constants, and literals are used interchangeably. 

For example, “const int = 5;“, is a constant expression and the value 5 is referred to as a constant integer literal. There are 4 types of literal in C and five types of literal in C++. 

  • Integer literal
  • Float literal
  • Character literal
  • String literal
    Types of Literals in C/C++

1) Integer Literals

Integer literals are used to represent and store the integer values only. Integer literals are expressed in two types i.e.

A) Prefixes: The Prefix of the integer literal indicates the base in which it is to be read.

For Example:

0x10 = 16

Because 0x prefix represents a HexaDecimal base. So 10 in HexaDecimal is 16 in Decimal. Hence the value 16.

There are basically represented into 4 types:

a. Decimal-literal(base 10): A non-zero decimal digit followed by zero or more decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).

Example:

56, 78

b. Octal-literal(base 8): a 0 followed by zero or more octal digits(0, 1, 2, 3, 4, 5, 6, 7).

Example:

045, 076, 06210

c. Hex-literal(base 16): 0x or 0X followed by one or more hexadecimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F).

Example:

0x23A, 0Xb4C, 0xFEA

d. Binary-literal(base 2): 0b or 0B followed by one or more binary digits(0, 1).

Example:

0b101, 0B111

B) Suffixes: The Prefix of the integer literal indicates the type in which it is to be read.

For example:

12345678901234LL 

indicates a long long integer value 12345678901234 because of the suffix LL

These are represented in many ways according to their data types.

  • int: No suffix is required because integer constant is by default assigned as an int data type.
  • unsigned int: character u or U at the end of an integer constant.
  • long int: character l or L at the end of an integer constant.
  • unsigned long int: character ul or UL at the end of an integer constant.
  • long long int: character ll or LL at the end of an integer constant.
  • unsigned long long int: character ull or ULL at the end of an integer constant.

Example:

#include <stdio.h>
  
int main()
{
  
    // constant integer literal
    const int intVal = 10;
  
    printf("Integer Literal:%d \n", intVal);
    return 0;
}

Output:

Integer Literal:10

2) Floating-Point Literals

These are used to represent and store real numbers. The real number has an integer part, real part, fractional part, and exponential part. The floating-point literals can be stored either in decimal form or exponential form. While representing the floating-point decimals one must keep two things in mind to produce valid literal:

  • In the decimal form, one must include the decimal point, exponent part, or both, otherwise, it will lead to an error.
  • In the exponential form, one must include the integer part, fractional part, or both, otherwise, it will lead to an error.

A few floating-point literal representations are shown below:

Valid Floating Literals:

10.125
1.215-10L
10.5E-3

Invalid Floating Literals:

123E
1250f
0.e879

Example:

Output:

Floating point literal: 4.14

3) Character Literal

This refers to the literal that is used to store a single character within a single quote. To store multiple characters, one needs to use a character array. Storing more than one character within a single quote will throw a warning and display just the last character of the literal. It gives rise to the following two representations:

A. char type: This is used to store normal character literal or narrow-character literals. This is supported by both C and C++.

Example:

// For C
char chr = 'G';

// For C++
char chr = 'G';

B. wchar_t type: This literal is supported only in C++ and not in C. If the character is followed by L, then the literal needs to be stored in wchar_t. This represents a wide-character literal.

Example:

// Not Supported For C

// For C++
wchar_t chr = L'G';

Example:

#include <stdio.h>
  
int main()
{
    // constant char literal
    const char charVal = 'A';
  
    printf("Character Literal: %c\n",
        charVal);
    return 0;
}

Output:

Character Literal: A

Escape Sequences: There are various special characters that one can use to perform various operations.

4) String Literals

String literals are similar to that character literals, except that they can store multiple characters and uses a double quote to store the same. It can also accommodate the special characters and escape sequences mentioned in the table above. We can break a long line into multiple lines using string literal and can separate them with the help of white spaces.

Example:

// For C
char stringVal[] = "GeeksforGeeks";

// For C++
string stringVal = "GeeksforGeeks"

Example:

Output:

Welcome
To
Geeks    For    Geeks

5) Boolean Literals

This literal is provided only in C++ and not in C. They are used to represent the boolean datatypes. These can carry two values:

  • true: To represent True value. This must not be considered equal to int 1.
  • false: To represent a False value. This must not be considered equal to int 0.

Example:

// C++ program to show Boolean literals
  
#include <iostream>
using namespace std;
  
int main()
{
    const bool isTrue = true;
    const bool isFalse = false;
  
    cout << "isTrue? "
        << isTrue << "\n";
    cout << "isFalse? "
        << isFalse << "\n";
  
    return 0;
}

Output:

isTrue? 1
isFalse? 0

Basic Input and Output in C

C language has standard libraries that allow input and output in a program. The stdio.h or standard input output library in C that has methods for input and output.

scanf()

The scanf() method, in C, reads the value from the console as per the type specified. Syntax:

scanf(“%X”, &variableOfXType); where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable and & is the address operator in C, which tells the compiler to change the real value of this variable, stored at this address in the memory.

printf()

The printf() method, in C, prints the value passed as the parameter to it, on the console screen. Syntax:

printf(“%X”, variableOfXType); where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable and & is the address operator in C, which tells the compiler to change the real value of this variable, stored at this address in the memory.

How to take input and output of basic types in C?

The basic type in C includes types like int, float, char, etc. Inorder to input or output the specific type, the X in the above syntax is changed with the specific format specifier of that type. The Syntax for input and output for these are:

  • Integer:
Input: scanf("%d", &intVariable);
Output: printf("%d", intVariable);
  • Float:
Input: scanf("%f", &floatVariable);
Output: printf("%f", floatVariable);
  • Character:
Input: scanf("%c", &charVariable);
Output: printf("%c", charVariable);

Please refer Format specifiers in C for more examples. 

C

// C program to show input and output
 
#include <stdio.h>
 
int main()
{
 
    // Declare the variables
    int num;
    char ch;
    float f;
 
    // --- Integer ---
 
    // Input the integer
    printf("Enter the integer: ");
    scanf("%d", &num);
 
    // Output the integer
    printf("\nEntered integer is: %d", num);
 
    // --- Float ---
   
    //For input Clearing buffer
      while((getchar()) != '\n');
 
    // Input the float
    printf("\n\nEnter the float: ");
    scanf("%f", &f);
 
    // Output the float
    printf("\nEntered float is: %f", f);
 
    // --- Character ---
 
    // Input the Character
    printf("\n\nEnter the Character: ");
    scanf("%c", &ch);
 
    // Output the Character
    printf("\nEntered character is: %c", ch);
 
    return 0;
}
Output:
Enter the integer: 10
Entered integer is: 10

Enter the float: 2.5
Entered float is: 2.500000

Enter the Character: A
Entered Character is: A

How to take input and output of advanced type in C?

The advanced type in C includes type like String. In order to input or output the string type, the X in the above syntax is changed with the %s format specifier. The Syntax for input and output for String is:

Input: scanf("%s", stringVariable);
Output: printf("%s", stringVariable);

Example: 

C

// C program to show input and output
  
#include <stdio.h>
  
int main()
{
  
    // Declare string variable
    // as character array
    char str[50];
  
    // --- String ---
    // To read a word
  
    // Input the Word
    printf("Enter the Word: ");
    scanf("%s\n", str);
  
    // Output the Word
    printf("\nEntered Word is: %s", str);
  
    // --- String ---
    // To read a Sentence
  
    // Input the Sentence
    printf("\n\nEnter the Sentence: ");
    scanf("%[^\n]\ns", str);
  
    // Output the String
    printf("\nEntered Sentence is: %s", str);
  
    return 0;
}
Output:
Enter the Word: GeeksForGeeks
Entered Word is: GeeksForGeeks

Enter the Sentence: Geeks For Geeks
Entered Sentence is: Geeks For Geeks
Here are some key details about the C programming language:

Syntax and Structure:
C uses a structured syntax with a small number of keywords and constructs.
The basic unit of a C program is a function, which contains statements that perform actions or computations.

Data Types:
C supports basic data types such as int (integer), char (character), float (floating-point number), and double (double-precision floating-point number).
It also supports derived data types like arrays, structures, and pointers.

Pointers:
Pointers are a powerful feature of C, allowing manipulation of memory addresses and enabling dynamic memory allocation.
Pointers are used for tasks such as accessing array elements, working with strings, and managing memory.

Memory Management:
C provides manual memory management through functions like malloc, calloc, realloc, and free, which allow you to allocate and deallocate memory at runtime.

Control Structures:
C includes control structures like if, else, switch, while, for, and do-while to control the flow of program execution.

Functions:
C functions are self-contained blocks of code that perform specific tasks.
Functions can have parameters and return values.
The main function is the entry point of a C program.

Modularity:
C supports modularity through header files (.h files) that contain function prototypes and macro definitions.
Source files (.c files) include headers and contain the actual function implementations.

Standard Library:
C comes with a standard library containing a wide range of functions for performing common tasks, such as string manipulation, file I/O, memory allocation, and more.

Preprocessor Directives:
The C preprocessor processes directives starting with # before the code is compiled.
Common preprocessor directives include #include for including header files, #define for defining macros, and #ifdef/#ifndef for conditional compilation.

Portability:
C programs are highly portable because they can be compiled on different platforms with minimal changes.
However, platform-specific code may still be required for certain functionalities.

Standardization:
The C language has evolved over the years, and different versions have been standardized.
The ANSI C (C89) and ISO C (C99, C11, etc.) standards specify the language features and libraries.

Coding Practices:
Good coding practices include using meaningful variable and function names, proper indentation, comments, and modular design.

Post a Comment

0 Comments