Size of Char in C++

Sep 28, 2020 at 10:30am
Hello,

Could you please explain this?

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
using namespace std;


int main()
{
	cout << sizeof('A') << endl; //1 Byte // It's OK.

	cout << sizeof('ACBP')<<endl; //4 Byte // Why?

	cout << sizeof('AC') << endl; //4 Byte // Why?

	
	cout << sizeof("ACBP") << endl; //5 Byte // Why?


	return 0;
}
Sep 28, 2020 at 10:53am
'ACBP' and 'AC' are interpreted as numbers. If you look at this in hex you get 0x41434250 and 0x4143 - with each 2-digit hex being the ASCII representation of the char - A is 0x41 and C is 0x43. The size of an int on your system is 4 bytes. Hence sizeof() returns 4.

"ACBP" is a null-terminated string - hence 5 bytes. 4 for the chars plus one for the null terminator. This is stored as 0x4143425000
Sep 28, 2020 at 11:50am
'ACBP' and 'AC' are examples of Multi Char Constants. The compiler will pack these into an int.

This effort is on a 'best effort' basis. You may also notice that 'ABSCEF' also has a size of 4 bytes (because an int on your machine is 4 bytes). Just to be clear, you shouldn't be using these. There's more on the matter here.
https://zipcon.net/~swhite/docs/computers/languages/c_multi-char_const.html
Sep 29, 2020 at 7:49am
Thank you, according your link, I read and wrote an example code, but my code doesn't print anything.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main()
{
	char TAG = 'ABC';

	switch (TAG)
	{
	case 'ABC':
		printf_s("ONE");
		break;
	case 'DBC':
		printf_s("TWO");
		break;
	case 'FBC':
		printf_s("THREE");
		break;
	}


	return 0;
}

Last edited on Sep 29, 2020 at 7:49am
Sep 29, 2020 at 9:21am
Why don't you get a book about the C language and start learning ?
Sep 29, 2020 at 9:26am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main()
{
	char TAG = 'ABC';

	printf("sizeof('ABC') = %u\n", sizeof('ABC'));
	printf("sizeof(char) = %u\n", sizeof(char));
	printf("TAG = '%c'", TAG);

	switch (TAG)
	{
	case 'ABC':
		printf("ONE");
		break;
	case 'DBC':
		printf("TWO");
		break;
	case 'FBC':
		printf("THREE");
		break;
	}


	return 0;
}
Output:
sizeof('ABC') = 4
sizeof(char) = 1
TAG = 'C'
Sep 29, 2020 at 9:47am
'ABC' is packed into an int - but TAG is typed as a char. Try:

 
int TAG = 'ABC';


Note that using muilt-char constants are not recommended.
Last edited on Sep 29, 2020 at 9:49am
Sep 29, 2020 at 12:34pm
@thmm
I'm reading a book right now.
Sep 29, 2020 at 1:28pm
Reading a book about C isn't particularly helpful, unless you're going to read the standard in depth.

It's not often used, and like Duff's Device and similar techniques, are pretty much obsoleted by the quality of modern compilers.
Topic archived. No new replies allowed.