Skip to content
Related Articles

Related Articles

Type Difference of Character Literals in C and C++

Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 19 May, 2022

Every literal (constant) in C/C++ will have a type of information associated with it. In both C and C++, numeric literals (e.g. 10) will have int as their type. It means sizeof(10) and sizeof(int) will return the same value.

If we compile what we have said in terms of code then it will look something like this.

Example:

C++




#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    cout<<sizeof(10)<<endl;
     cout<<sizeof(int)<<endl;
    return 0;
}

Output:

4
4

However, character literals (e.g. ‘V’) will have different types, sizeof(‘V’) returns different values in C and C++. In C, a character literal is treated as int type whereas, in C++, a character literal is treated as char type (sizeof(‘V’) and sizeof(char) are the same in C++ but not in C. Let us see this interesting behaviour through an example.

C




#include <stdio.h>
int main()
{
printf("%lu", sizeof('V'));
printf("\n");
printf("%lu", sizeof(char));
return 0;
}
  
  
  
// Output
// 4
// 1

C++




#include<bits/stdc++.h>
using namespace std;
  
int main()
{
cout<<sizeof('V')<<endl;
cout<<sizeof(char)<<endl;
return 0;
}
  
  
  
  
// Output
// 1
// 1

Result of above program:

  • C result – sizeof(‘V’) = 4 and sizeof(char) = 1 
  • C++ result – sizeof(‘V’) = 1 and sizeof(char) = 1

More precisely we can say that in C, sizeof(‘V’) will be treated as long unsigned int, let us see an example to make things more clear.

C




#include <stdio.h>
int main()
{
    printf("%d", sizeof('V'));
    return 0;
}

Output: it will give this error.

source.c: In function 'main':
source.c:7:10: warning: format '%d' expects argument of type 'int', but argument 2 has type 'long unsigned int' [-Wformat=]
    7 | printf("%d", sizeof('V'));
      |         ~^   ~~~~~~~~~~~
      |          |   |
      |          int long unsigned int
      |         %ld

Such behavior is required in C++ to support function overloading. An example will make it more clear. Predict the output of the following C++ program. 

C++




#include<bits/stdc++.h>
using namespace std;
  
void foo(char c)
{
   printf("From foo: char");
}
void foo(int i)
{
   printf("From foo: int");
}
    
int main()
{
   foo('V');
   return 0;
}

Output:

From foo: char

The compiler must call 

void foo(char);

since ‘V’ type is char

This article is contributed by Venki. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!