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:



C Programming Keywords and Concepts

1. auto

  • Definition: The auto storage class variable is declared inside a function or a block, and its scope is limited to that block. By default, auto variables have garbage values until assigned.
  • Example:
 
#include <stdio.h>
 
int printvalue() {
    auto int a = 10;
    printf("%d", a);
}
 
int main() {
    printvalue();
    return 0;
}

Output: 10

2. break and continue

  • Definition: The break statement terminates the innermost loop, while continue skips the current iteration and continues with the next.
  • Example:
 
#include <stdio.h>
 
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

3. switch, case, and default

  • Definition: The switch statement is an alternative to the if-else ladder, allowing multiple operations for different values of a variable.
  • Example:
 
#include <stdio.h>
 
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

4. char

  • Definition: The char keyword declares a character variable.
  • Example:
 
#include <stdio.h>
 
int main() {
    char c = 'a';
    printf("%c", c);
    return 0;
}

Output: a

5. const

  • Definition: The const keyword defines a variable whose value cannot be changed.
  • Example:
 
#include <stdio.h>
 
int main() {
    const int a = 11;
    a = a + 2// This line will cause an error
    printf("%d", a);
    return 0;
}

Output: error: assignment of read-only variable 'a'

6. do-while

  • Definition: The do statement creates a loop that executes once and checks its condition afterward.
  • Example:
 
#include <stdio.h>
 
int main() {
    int i = 1;
    do {
        printf("%d ", i);
        i++;
    } while (i <= 5);
    return 0;
}

Output: 1 2 3 4 5

7. double and float

  • Definition: Both are data types for decimal variables; double has 15 decimal digits, while float has 7.
  • Example:
 
#include <stdio.h>
 
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

8. if-else

  • Definition: Used for decision-making; executes code blocks based on a condition.
  • Example:
 
#include <stdio.h>
 
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

9. enum

  • Definition: enum is a user-defined data type that holds a list of user-defined integer constants.
  • Example:
 
#include <stdio.h>
 
enum week {Mon, Tue, Wed, Thur, Fri, Sat, Sun};
 
int main() {
    enum week day = Wed;
    printf("%d", day);
    return 0;
}

Output: 2

10. extern

  • Definition: The extern keyword declares a variable or function that has external linkage outside the file.
  • Example:
 
#include <stdio.h>
 
extern int a;
 
int main() {
    printf("%d", a);
    return 0;
}

11. for

  • Definition: The for keyword is used to create a for-loop.
  • Example:
 
#include <stdio.h>
 
int main() {
    for (int i = 0; i < 5; i++) {
        printf("%d ", i);
    }
    return 0;
}

Output: 0 1 2 3 4

12. goto

  • Definition: The goto statement transfers control to a specified label.
  • Example:
 
#include <stdio.h>
 
void printNumbers() {
    int n = 1;
    
label:
    printf("%d ", n);
    n++;
    if (n <= 10) goto label;
}
 
int main() {
    printNumbers();
    return 0;
}

Output: 1 2 3 4 5 6 7 8 9 10

13. int

  • Definition: The int keyword is used to declare integer-type variables.
  • Example:
 
#include <stdio.h>
 
void sum() {
    int a = 10, b = 20;
    int sum = a + b;
    printf("%d", sum);
}
 
int main() {
    sum();
    return 0;
}

Output: 30

14. short, long, signed, and unsigned

  • Definition: These keywords define integer types with various ranges.
  • Example:
 
#include <stdio.h>
 
int main() {
    short int a = 12345;
    signed int b = -34;
    unsigned int c = 12;
    long int d = 99998L;
    
    printf("Integer value with a short int data: %hd\n", a);
    printf("Integer value with a signed int data: %d\n", b);
    printf("Integer value with an unsigned int data: %u\n", c);
    printf("Integer value with a long int data: %ld\n", 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

15. return

  • Definition: The return statement sends a value back to where the function was called.
  • Example
  • #include <stdio.h>
     
    int sum(int x, int y) {
        return x + y;
    }
     
    int main() {
        int num1 = 10;
        int num2 = 20;
        printf("Sum: %d", sum(num1, num2));
        return 0;
    }

    OutputSum: 30

16. sizeof

  • Definition: The sizeof keyword returns the size of a data type or variable in bytes.
  • Example:
 
#include <stdio.h>
 
int main() {
    int x = 10;
    printf("%d", sizeof(x));
    return 0;
}

Output: 4

17. register

  • Definition: register variables are stored in CPU registers for faster access.
  • Example:
 
register char c = 's';

18. static

  • Definition: The static keyword creates static variables that retain their value even after their scope ends.
  • Example:
 
static int num;

19. typedef

  • Definition: typedef creates an alias for an existing type.
  • Example:
 
typedef unsigned long ulong;

20. volatile

  • Definition: volatile informs the compiler that a variable can change unexpectedly.
  • Example:
 
volatile int a;

21. struct

  • Definition: The struct keyword defines a structure, a user-defined data type to group different data types.
  • Example:
 
struct student {
    int roll;
    char name[50];
};

22. union

  • Definition: The union keyword defines a union, a user-defined data type that can store different data types in the same memory location.
  • Example:
 
union data {
    int i;
    float f;
    char c;
};

23. #define

  • Definition: The #define directive creates symbolic constants or macros.
  • Example:
 
#define PI 3.14

24. #include

  • Definition: The #include directive is used to include header files.
  • Example:
 
#include <stdio.h>




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

  • Discussion: C is fundamentally a procedural programming language, meaning it follows a sequence of steps to execute tasks. Each task can be broken down into functions, making the code modular and reusable.
  • Example: Consider a simple program that performs arithmetic operations. Different functions can handle addition, subtraction, etc.:

c

 

int add(int a, int b) {

    return a + b;

}

 

int subtract(int a, int b) {

    return a - b;

}

2. Fast and Efficient

  • Discussion: C is often referred to as a "low-level" language because it allows direct manipulation of hardware and memory. This makes C programs fast, as they execute directly on the machine without the overhead that comes with higher-level languages.
  • Example: In performance-critical applications, such as operating systems, C is the go-to language for its efficiency. Code that requires intensive computation often sees better performance in C compared to interpreted languages like Python.

3. Modularity

Importance of Understanding C

  • Understanding the advantages and disadvantages of C is vital for several reasons:

    • Choosing the Right Language: Helps developers select the appropriate programming language for their projects.
    • Writing Efficient Code: Encourages the creation of optimized code for performance-critical applications.
    • Avoiding Common Pitfalls: Awareness of potential issues helps in writing secure code.
    • Effective Communication: Knowledge of C facilitates collaboration among developers.

Compiler Differences: A Case Study

Example 1

  • Consider the following simple C program:

    c
     

Example 2

Compiler Compliance

Conclusion

4. Statically Typed

  • Discussion: C’s static typing means that variable types are checked at compile time, reducing runtime errors. While this helps catch errors early, it requires developers to be explicit about data types.
  • Example:

c

 

int num = 10; // Must declare variable type

5. General-Purpose Language

  • Discussion: C’s versatility allows it to be used in various applications, from system software to embedded systems, demonstrating its wide applicability across industries.
  • Example: Major operating systems, such as Linux and Windows, are primarily written in C.

6. Rich Set of Built-in Operators

  • Discussion: C offers a diverse set of operators (arithmetic, relational, logical, bitwise, etc.) that facilitate the writing of complex algorithms with less code.
  • Example:

c

 

int a = 5, b = 10;

int result = a + b; // Arithmetic operator

7. Libraries with Rich Functions

  • Discussion: C has a robust standard library (e.g., stdio.h, stdlib.h, string.h) that provides numerous functions for handling input/output, memory allocation, and string manipulation, which simplifies development.
  • Example:

c

 

#include <stdio.h>

 

int main() {

    printf("Hello, World!\n");

    return 0;

}

8. Middle-Level Language

  • Discussion: C is termed a middle-level language because it combines the features of high-level languages (ease of use) with the low-level capabilities (direct hardware access) of assembly language.
  • Example: System calls in C can interact directly with hardware while providing higher-level abstractions for ease of programming.

9. Portability

  • Discussion: Programs written in C can often be compiled and run on different machines with little or no modification. This makes C a favored language for cross-platform applications.
  • Example: A simple "Hello World" program can be compiled on various operating systems (Linux, Windows, macOS) with the same source code.

10. Easy to Extend

  • Discussion: Existing C programs can be enhanced by adding new features without major rewrites, making it a flexible choice for long-term projects.
  • Example: Adding new functionality to a library or modular program can be done by creating new functions or modules that integrate seamlessly with the existing codebase.

Introduction to C Standards

  • Discussion: The evolution of C through various standards (C89/C90, C99, C11, C18) has introduced features and enhancements that keep it relevant. Understanding which standard a compiler supports is essential for writing compatible code.

Advantages of C

  • Efficiency: Ideal for system-level programming, embedded systems, and high-performance applications.
  • Portability: C programs can be run across multiple platforms.
  • Low-Level Access: Allows direct manipulation of hardware and memory, making it suitable for operating systems and device drivers.
  • Large User Community: Abundant resources, libraries, and community support available.

Disadvantages of C

  • Steep Learning Curve: The syntax and low-level features can be daunting for beginners.
  • Memory Management: Manual memory management can lead to leaks and bugs if not handled correctly.
  • Lack of Object-Oriented Features: Unlike languages like C++ or Java, C does not support OOP natively, making certain design patterns more challenging to implement.
  • Security Vulnerabilities: Care must be taken to avoid buffer overflows and other security issues due to manual memory management.

 

Importance of Understanding C

Understanding the advantages and disadvantages of C is vital for several reasons:

  • Choosing the Right Language: Helps developers select the appropriate programming language for their projects.
  • Writing Efficient Code: Encourages the creation of optimized code for performance-critical applications.
  • Avoiding Common Pitfalls: Awareness of potential issues helps in writing secure code.
  • Effective Communication: Knowledge of C facilitates collaboration among developers.

Compiler Differences: A Case Study

Example 1

Consider the following simple C program:

c 
void main() { }
  • GCC: Fails because main must return an int.
  • Turbo C: Compiles successfully, allowing void main().

Example 2

Another example demonstrates different compiler outputs:


#include <stdio.h>
int main()
{
    int i = 1;
    printf("%d %d %d\n", i++, i++, i);
    return 0;
}
  • G++ on Linux: Outputs 2 1 3.
  • SunStudio C++: Outputs 1 2 3.

Compiler Compliance

To determine which behavior is correct, we refer to the C standard. The C standard specifies rules that compilers must follow, thus ensuring consistent behavior across different platforms.

Conclusion

The C programming language is powerful and versatile, suitable for various applications. Understanding its features, advantages, and the implications of different standards is crucial for developers. As programming continues to evolve, C remains a fundamental language that serves as the backbone of many modern technologies.



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.


Understanding Comments and Variables in C

In the C programming language, comments and variables play crucial roles in enhancing code readability and storing data. Let's dive into the types of comments in C and how to effectively use variables.

Types of Comments in C

In C, there are two types of comments:

1. Single-line Comment

A single-line comment in C starts with //. It extends to the end of the line, and no end symbol is needed.

Syntax of Single-Line Comment:

c
 
// This is a single line comment

Example:

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

Output:

css
 
Welcome to CodeWithJay

Comment at End of Code Line: You can also create comments at the end of a line of code using a single-line comment. However, it’s generally better practice to place comments 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 CodeWithJay"); // comment here
    return 0;
}

Output:

 
Welcome to CodeWithJay

2. Multi-line Comment

A multi-line comment in C begins with /* and ends with */. Any text between these symbols is ignored by the compiler and can span multiple lines.

Syntax of Multi-Line Comment:

c
 
/* Comment starts
   continues
   continues
   Comment ends */

Example:

c
 
/* C program to illustrate the 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 CodeWithJay");
    return 0;
}

Output:

 
Welcome to CodeWithJay

What is a Variable in C?

A variable in C is a named memory location that stores data of different types. Variables are fundamental building blocks of a C program, allowing developers to use meaningful names instead of memory addresses. The size of a variable depends on the data type it stores.

C Variable Syntax

To declare a variable in C, you specify the type and name of the variable.

Syntax:

c
 
data_type variable_name = value;    // Defining a single variable
// or
data_type variable_name1, variable_name2;    // Defining multiple variables

Where:

  • data_type: Specifies the type of data the variable can store.
  • variable_name: The name given to the variable.
  • value: The value assigned to the variable.

Examples:

c
 
int var;    // Integer variable
char a;     // Character variable
float fff;  // Float variable

Variable Declaration, Definition, and Initialization

1.     C Variable Declaration: Declaring a variable informs the compiler about its existence and data type. No memory is allocated during declaration.

c
 
int var;  // Declaration

2.     C Variable Definition: In this phase, the compiler allocates memory for the variable. Until it’s initialized, it holds a random garbage value.

c
 
int var;  // Declaration and Definition

3.     C Variable Initialization: This is the process of assigning a meaningful value to a variable.

c
 
var = 10; // Initialization
// or
int var = 10; // Declaration, Definition, and Initialization

How to Use Variables in C

Here's an example demonstrating variable declaration, definition, and initialization in C:

c
 
// C program to demonstrate declaration, definition, and initialization
#include <stdio.h>
 
int main()
{
    // Declaration with definition
    int defined_var;
 
    printf("Defined_var: %d\n", defined_var); // May display garbage value
 
    // 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\n", 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

When naming variables in C, follow these rules:

  • A variable name can contain alphabets, digits, and underscores.
  • It must start with an alphabet or an underscore (not a digit).
  • No whitespace is allowed in variable names.
  • A variable name must not be a reserved word or keyword.

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