-3

I'm learning c++ and our Prof. wants us to understand whether the things we have learnt would/wouldn't function in other languages.

Would the following code in python print "I love my dog ..." (for every array instance) AND "my favourite dog is jack" or just the latter?

pets = ['flufffy', "jack", 'larry']
for a in pets:
    print "I love my dog %s" % a
print "My favourite dog is %s" % pets[1]

in c++ if the a was not declared the loop wouldn't compile/run properly if mi correct.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Wise
  • 69
  • 7

1 Answers1

2

In Python, assignment includes implicit declaration (it's just that declaration only means "the name exists", and doesn't force a static type).

for a in pets:

works just fine (so all the lines you expect are printed, the loop isn't skipped for whatever reason you seem to expect), because the for loop assigns to a, implicitly declaring it. It's not like C++ where there would need to be a declaration like std::string a (either before or in the loop) or auto a (in the loop) to declare that a exists with a known type.

To be clear, C++ would only require a to be declared (and it could be done in the loop itself, e.g. for (const auto& a : pets) {), not specifically initialized, to make the loop work.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271