Open In App

What is the difference between single quoted and double quoted declaration of char array?

Last Updated : 06 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C programming, the way we declare and initialize a char array can differ based on whether we want to use a sequence of characters and strings. They are basically same with difference only of a '\0' NULL character.

Double quotes automatically include the null terminator, making the array a string literal that can be safely used with string functions. On the other hand, single quotes are used for declaring an array of individual characters, without any null terminator, making it more suitable for scenarios where you need to work directly with the characters and manage their memory manually.

Single-quoted Declaration

When you use single quotes to define an array of characters, each element in the array is a single-character literal. It is essentially a sequence of individual characters that do not automatically add a null terminator ('\0'), unlike a string.

Example:

C
#include <stdio.h>

int main() {
  
    // No null terminator
    char arr[] = { 'g', 'e', 'e', 'k', 's' };  

    // Print individual characters manually
    for (int i = 0; i < 5; i++) {
        printf("%c", arr[i]);
    }
    printf("\n");

    return 0;
}

Output
geeks

However, if you try to print it using %s in printf, it won't work as expected since there’s no null terminator:

printf("%s", arr); // Incorrect, will cause undefined behavior

Double-quoted Declaration

When you use double quotes, the C compiler automatically creates a string literal, which is an array of characters that ends with a null terminator ('\0').

Example:

C
#include <stdio.h>

int main() {
   
    // Null terminator included automatically
    char arr[] = "geeks";  

    // Print using string format specifier
    // Correct, prints "geeks"
    printf("%s", arr); 

    return 0;
}

Output
geeks

This works because the string literal "geeks" automatically includes the null terminator ('\0'), allowing functions like printf to correctly identify the end of the string.


Similar Reads