C + + face question 5: It is recommended not to use the size of the sizeof arithmetic group in the function

Source: Internet
Author: User


C + + face question 5: It is recommended not to use the size of the sizeof arithmetic group in the function
#include <iostream>usingNamespace::STD;voidFooConst int[]);intMain () {intarr[3] = {1,2,3};cout<<"in main array size:"<<sizeof(arr)/sizeof(int) <<endl; Foo (arr);}voidFooConst intArr[]) {cout<<"in foo array size:"<<sizeof(arr)/sizeof(int) <<endl;} Output:in MainArraySize3in FooArraySize1

Note: in C + + functions, if an array is passed in as a parameter, the array is degraded to a pointer, so the length of the array is not known.
"Imperfect C + +" can use a small technique to find a function of the length of an array, using a template to intercept the length directly, because the input is an array of references (note that the array reference as the syntax of the parameter), so it can be in the compilation period to identify the pointer.

template <typenameint N>int arr_size(T (&arr)[N]){    return N;//函数直接返回作为参数传入的数组的长度。}

C + + face question 5: It is recommended not to use the size of the sizeof arithmetic group in the function

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.