Sizeof differences between character constants in C and C ++

Source: Internet
Author: User

In C:

# Include <stdio. h>
Int main (){
Char A = 'a ';
Printf ("size of char: % d \ n", sizeof ());
Printf ("size of char: % d \ n", sizeof ('A '));
Return 0;
}
Output:

Size of char: 1
Size of char: 4

In 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;
}
Output:

Size of char: 1
Size of char: 1
Why is the value returned by sizeof ('A') different from that returned by C ++?

According to the c99 standard, 'A' is called an integer character constant and is regarded as an int type. Therefore, it occupies 4 bytes on 32-bit machines.
According to the iso c ++ standard, 'A' is called character literal, which is regarded as a char type and occupies 1 byte.

C99:
An integer character constant is a sequence of one or more multibyte characters enclosed
In single-quotes, as in 'X'. An integer character constant has type Int.

C ++ 2003:
A character literal is one or more characters enclosed in single quotes, as in 'X', optionally preceded by the letter L, as in L 'x '. A character literal that does not begin with L is an ordinary character literal, also referred to as a narrow-character literal. an ordinary character literal that contains a single c-Char has type char, with value equal to the numerical value of the encoding of the C-char in the execution character set. an ordinary character literal that contains more than one C-Char is a multicharacter literal. A multicharacter literal has type int and implementation-defined value.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.