views:

90

answers:

2

I'm reviewing for a test, and I am stumped by this question.

Consider the following declarations:

enum CategoryType {HUMANITIES, SOCIALSCIENCE, NATURALSCIENCE}; 
const int NUMCOURSES = 100; 
struct CourseRec 
{ 
         string courseName; 
         int courseNum; 
         CategoryType courseCategory; 
}; 
typedef CourseRec CourseList [NUMCOURSES]; 
CourseList courses; 
int index1, index2; 
  1. What is the data type of the expression courses[index1] .courseName[index2] ?

(a) CourseList (b) CourseRec (c) string (d) char (e) none; the expression is syntactically invalid

I thought that the answer would be string, since courseName is a string, or maybe even CourseRec, since it is in the struct, but the answer is (d)char. Why is this a char data type? Any help is greatly appreciated.

A: 

A string is an array of char, so taking anyString[0] returns the char in the first position of the string array.

Jaymz
A C++ string is *not* simply an array of char, but you are correct in that the `[]` operator on a C++ string does return a char corresponding to the specified position in the string.
Tyler McHenry
It actually returns a reference to the char, not the char by-value.
John Dibling
+8  A: 

Let's go step by step:

courses[index1] .courseName[index2]

  • courses is array of CourseRec
  • courses[index1] is CourseRec
  • courses[index1] .courseName is string
  • courses[index1] .courseName[index2] is char *

* - actually it is char&

Andrey
Georg Fritzsche
This is how a programmer thinks when they are facing some crazy construct. +1
John Dibling
Thanks for the help!
dubya
Georg Fritzsche