Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for pointer to char in C

Tags:

c++

c

pointers

Let us have the variable char *s;

I know if it's declared in global scope, its value should be 0;

If it's declared in local scope, its value is undefined (it may be 0 though).

I've got a question in test which sounds like this 'What will be the value of the pointer defined as

char* s

a) null
b) empty string
c) undefined

I'm really confused what answer I should choose, because if it's declared in global scope, well, the value would be null (i guess). If it's declared in local scope, undefined (though when I tried it's zero), and when I try to cout it, nothing is printed (no segmentation fault, why?), that means it's an empty string (or is cout that awesome?).

like image 935
cliffroot Avatar asked May 31 '14 19:05

cliffroot


1 Answers

The question you quoted is most likely written by a person who didn't fully understand the issue. As you correctly noted, the initial value of such pointer greatly depends on the context: where and how it is defined (local, static, aggregate member?). So, the correct answer should be an expanded one that explains these dependencies. It is weird to attempt to answer such question in a "multiple choice, only one of many" fashion.

Of course, in very general and most formally pedantic sense, the correct answer is the one that says "undefined", since in general case, not knowing where it is defined, we have to "assume the worst". But I doubt the author of the test realized that.

like image 138
AnT Avatar answered Oct 09 '22 00:10

AnT