包含多个字符的字符常量

A character constant with more then one character

本文关键字:字符常量 字符 包含多      更新时间:2023-10-16

我正在检查我在stackoverflow上看到的一些答案,并以一种根据非常有经验的程序员不应该工作的方式更改了一行,令人惊讶的是它做到了。有人能解释一下为什么这是可能的吗?问题是一个字符常量与多个字符(我使用Visual Studio 2013)

// stack.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using std::cout;

int * foo()
{
    int a = 5;
    return &a;
}
int main()
{
    int* p = foo();
    cout << *p << '  ';  // this line should not compile but it did???
    *p = 8;
    cout << *p << 'n';
}  

有人能解释一下为什么这是可能的吗?

因为语言允许这样的事情;它被称为多字符文字。用c++ 11 2.14.3/1的话说:

多字符文字类型为int,并且是由实现定义的价值。

通常,每个字符(足够短的字面值)将映射到int值的一个字节,因此'ab''ba'应该具有不同的值;要了解详细信息,请参考编译器的文档。