Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between char[N] and char (&)[N] in parameter list

Tags:

c++

c++11

The following code doesn't compile:

template <int N>
void f(char[N]) {}

int main() {
  char buf[10];
  f(buf);
}

If I change the char[N] to char (&)[N], it works. So what the difference between them?

like image 825
Kan Li Avatar asked Apr 16 '16 09:04

Kan Li


People also ask

Should I use CHAR or Nchar?

When to use what? If your column will store a fixed-length Unicode characters like French, Arabic and so on characters then go for NCHAR. If the data stored in a column is Unicode and can vary in length, then go for NVARCHAR. Querying to NCHAR or NVARCHAR is a bit slower then CHAR or VARCHAR.

What is the difference between CHAR N and VARCHAR N data types?

Difference between CHAR and VARCHAR datatypes: In CHAR, If the length of the string is less than set or fixed-length then it is padded with extra memory space. In VARCHAR, If the length of the string is less than the set or fixed-length then it will store as it is without padded with extra memory spaces.

Which is better CHAR or VARCHAR?

CHAR columns are fixed in size, while VARCHAR and VARCHAR(MAX) columns support variable-length data. CHAR columns should be used for columns that vary little in length. String values that vary significantly in length and are no longer than 8,000 bytes should be stored in a VARCHAR column.

What is diff between VARCHAR and NVARCHAR?

The key difference between varchar and nvarchar is the way they are stored, varchar is stored as regular 8-bit data(1 byte per character) and nvarchar stores data at 2 bytes per character. Due to this reason, nvarchar can hold upto 4000 characters and it takes double the space as SQL varchar.


1 Answers

You have been bitten by backwards compatibility with C. When you declare a function like:

int f(char c[10]);

You declare a function whose argument is of type char *. The compiler decays the argument type for you. The problem is:

int f(char c[5]);

declares the same function. This is the way C worked, and C++ retained it for compatability.

int f(char (&c)[10]);

Declares a function whose argument is of type "reference to array (length 10) of char". C didn't have references, so there is no need to maintain backwards compatibility.

int f(char (&c)[5]);

Declares a different function - with a different argument type.

like image 118
Martin Bonner supports Monica Avatar answered Oct 05 '22 20:10

Martin Bonner supports Monica