1

I was checking some answer I've seen on stackoverflow and altered a line in a way that shouldn't work according to a very experienced programmer, surprisingly it did. can anyone explain why it is possible? The issue is a character constant with more then one character (i'm using 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';
}  
Talmor
  • 53
  • 6
  • What are you testing with your code, multi-character literals or undefined behavior? If you only have a question about multi-character literals, remove the rest of the code that causes the undefined behavior, it's not relevant to the question and distracts from the actual question you have. – Some programmer dude Mar 12 '14 at 13:42

1 Answers1

3

can anyone explain why it is possible?

Because the language allows such a thing; it's called a multicharacter literal. In the words of C++11 2.14.3/1:

A multicharacter literal has type int and implementation-defined value.

Typically, each character (of a short enough literal) will map to one byte of the int value, so that 'ab' and 'ba' should have different values; for full details, you'll have to consult your compiler's documentation.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644