c++ - C++11: Type of string literal is "array of the appropriate number of const characters" -


c++11: type of string literal "array of appropriate number of const characters";

"bohr" therefore of type const char[5]

void f() {  char* p = "plato"; // error, accepted in pre-c++11-standard code  p[4] = 'e';        // error: assignment const } 

(which short excerpt of "the c++ programming language bjarne stroustrup (4th ed.)" on p. 176 in 7.3.2 "string literals") yet compiler (dev-c++11 5.6.2) either settings of iso-c++11 or gnu-c++11 doesn't warn or break compilation at

const char a[5] = "bohr"; const char *b = "bohr"; 

furthermore, question #2 @ cppquiz.org doesn't mention compiler breakage or other problems this: http://cppquiz.org/quiz/question/2

what output of below program in c+++11?

#include <iostream> #include <string>  void f(const std::string &) { std::cout << 1; }  void f(const void *) { std::cout << 2; }  int main() {   f("foo");   const char *bar = "bar";   f(bar); } 

before writing author, wanted ask advice here; hope can me?

edit: line

char* p = "plato"; // error, accepted in pre-c++11-standard code 

should, commented, not valid in c++-11-standard code, according latest book official creator of language, in

const char *b = "bohr"; 

there appears no problem in quiz compiler?

the type of string literal "bohr" indeed const char[5].

however, can implicitly casted const char * due to

§ 4.2 array-to-pointer conversion [conv.array]

an lvalue or rvalue of type “array of n t” or “array of unknown bound of t” can converted prvalue of type “pointer t”. result pointer first element of array.

edit:

i didn't realize confusion bjarne's statement // error, accepted in pre-c++11-standard code. well, compilers need stay backwards-compatible don't throw error, give warning. claim isn't wrong however, since far language standard goes, c++11 rules error.

from clang example:

warning: conversion string literal 'char *' deprecated [-wc++11-compat-deprecated-writable-strings]

and gcc:

warning: deprecated conversion string constant ‘char*’ [-wwrite-strings]


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -