Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify type of string (e.g. literal, array, pointer) passed to a function [duplicate]

Tags:

c++

c

string

I have a function, which takes a character array and its size:

void store_string (const char *p, size_t size); // 'p' & 'size' stored in map

The function is wrapped by a macro as:

#define STORE_STRING(X) store_string(X, sizeof(X))

My problem is that I want to somehow prohibit or inform user that only string literal should be passed to this function. Because, if any pointer or local array are stored inside the map then they might go out of scope and create a havoc!

Is there any compile-time way (preferred) or at least run-time way to do it?

like image 365
HiddenAngel Avatar asked Apr 28 '11 13:04

HiddenAngel


1 Answers

You can know it compile time, by simply changing your macro to:

#define STORE_STRING(X) store_string("" X, sizeof(X))

Usage:

char a[] = "abcd", *p;
STORE_STRING(a); // error
STORE_STRING(p); // error
STORE_STRING("abcd"); // ok
like image 186
iammilind Avatar answered Sep 21 '22 20:09

iammilind