David G
David G

Reputation: 96845

Why does this loop not work?

It's a very simple program. I have a function defined on the top and in the loop I am calling the function print.

But I am getting the following errors:

prog.cpp:5: error: variable or field ‘print’ declared void
prog.cpp:5: error: ‘a’ was not declared in this scope
prog.cpp: In function ‘int main()’:
prog.cpp:11: error: ‘print’ was not declared in this scope

Here it is:

#include <iostream>    
using namespace std;

void print( a ) {
    cout << a << endl;
}

int main() {
    for ( int i = 1; i <= 50; i++) {
        if ( i % 2 == 0 ) print( i );
    }

    return 0;
}

Upvotes: 0

Views: 1016

Answers (5)

Peter Leong
Peter Leong

Reputation: 99

#include <iostream>

using namespace std;

void print( int a ) {
    cout << a << endl;
}

int main() {
    for ( int i = 1; i <= 50; i++) {
        if ( i % 2 == 0 ) print( i );
    }

    return 0;
}

Upvotes: 0

inkooboo
inkooboo

Reputation: 2954

C++ doesn have dynamic types. So you need to specify type of "a" variable manually or use function template.

void print( int a ) {
    cout << a << endl;
}

template <typename T>
void print( T a ) {
    cout << a << endl;
}

Upvotes: 2

Roee Gavirel
Roee Gavirel

Reputation: 19463

change to:

void print( int a ) { // notice the int
    cout << a << endl;
}

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168836

Try this:

void print( int a ) {

Upvotes: 5

Fred Foo
Fred Foo

Reputation: 363817

You forgot to declare the type of a when defining print.

Upvotes: 7

Related Questions