user5280911
user5280911

Reputation: 763

Associativity between type cast and . in Visual Studio

Following is the code in question.

void SomeClass::Init( const vector<string>& args ) {
   int argc = (int)args.size(); 
   //... 
}

I work in Visual Studio 2015 Update 3 on Windows 7 64-bit.

My question is: according to my understanding of operator associativity, type cast (int) and member selector . has the same precedence (see the screenshot below excerpted from "C++ Primer, 5ed") so the evaluation order should be decided by associativity. But the associativity of this level is left, that is, the expression is evaluated from left to right. So (int)args is first evaluated, turning args into an int. Then the int version of args tries to call its size function which does not exist and therefore should cause a compiling error. But Visual Studio 2015 does not report any error and runs as expected: the expression on the right side calls size() function first and then convert the returned value to int. Why? Is my understanding of associativity wrong or am I missing anything? Thank you for your help.

enter image description here

Upvotes: 1

Views: 151

Answers (1)

songyuanyao
songyuanyao

Reputation: 173004

Note that what you're using is not function cast, but c-style cast, which has lower precedence than member access operator.

So (int)args.size() is equivalent to (int) (args.size()) and works well.

Upvotes: 1

Related Questions