Difference in size of ('a') in C/C++

Asked 1 years ago, Updated 1 years ago, 126 views

I learned that the size of char is 1 in C/C++ The result of printing('a') in C/C++ is different

From C:

#include <stdio.h>
int main() {
  printf("Size of char : %d\n",sizeof(char));
  return 0;
}

From C++:

#include <iostream>
int main() {
  std::cout<<"Size of char : "<<sizeof(char)<<"\n";
  return 0;
}

If you do it, it's going to be 1.

From C:

#include <stdio.h>
int main() {
  char a = 'a';
  printf("Size of char : %d\n",sizeof(a));
  printf("Size of char : %d\n",sizeof('a'));
  return 0;
}

If I do Size of char : 1 Size of char : 4

From C++:

#include <iostream>
int main() {
  char a = 'a';
  std::cout<<"Size of char : "<<sizeof(a)<<"\n";
  std::cout<<"Size of char : "<<sizeof('a')<<"\n";
  return 0;
}

If I do Size of char : 1 Size of char : 1

Why is that? Why is size of ('a') different?

c type

2022-09-22 22:38

1 Answers

In C, character type constants such as 'a' are actually int. That's why size of ('a') is output 4.

In C++, on the other hand, 'a' is char type. So the size of ('a') outputs 1.

C and C++ look similar, but they're different languages, so sometimes there's this difference.


2022-09-22 22:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.