_countof macro example

_countof() macro returns the number of elements present in the array. It is different from sizeof() , which returns the size of the array in bytes.

Syntax: size_t _countof(array); 

You should include the header file #include <stdlib.h> to use it.

Example1:

#include "stdafx.h"
#include "stdlib.h"

int _tmain(int argc, _TCHAR* argv[])
{
TCHAR buffer[100];
printf("Size of buffer is %d and _countof buffer is %d\n", sizeof(buffer), _countof(buffer));
return 0;
}

O/P: Size of buffer is 200 and _countof buffer is 100.

So from the above output you can see that ouput of sizeof and _countof is different, _countof returns the number of elements present in the array whereas sizeof returns the number of bytes occupied by the array.

Don't try to pass an pointer as argument to _countof, pass only array. You will get a compile time error . For example look at the following code below.

#include "stdafx.h"
#include "stdlib.h"

int _tmain(int argc, _TCHAR* argv[])
{
char *ptr;
printf("Size of ptr is %d and _countof ptr is %d\n", sizeof(ptr), _countof(ptr));
return 0;
}

This will give a compile time error: C2784



Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

PR, PN and PV Variable in Yocto