Type Difference of Character Literals in C and C++
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; } |
C
// C program to illustrate that 'sizeof(10)' with its type 'int' // will return the same value as of 'sizeof(int)' #include <stdio.h> int main( void ) { printf ( "%lu\n" , sizeof (10)); printf ( "%lu\n" , sizeof ( int )); return (0); } // This code is contributed by sarajadhav12052009 |
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.