Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't structs work in Xcode, when they do in Visual C++? Help needed!

Tags:

c++

xcode

For some reason, this very basic code will compile with no errors in Visual C++, but gives errors in XCode. I will need to know why, in order to continue working in Xcode for my Computer Science class.

#include <iostream>
#include <string>

using namespace std;

struct acct {        // bank account data
    int     num;      // account number
    string name;      // owner of account
    float   balance; // balance in account
};

int main() {

    acct account;

    cout << "Enter new account data: " << endl;
    cout << "Account number: ";
    cin  >> account.num;
    cout << "Account name: ";
    cin  >> account.name;
    cout << "Account balance: ";
    cin  >> account.balance;

    return 0;

}

It gives two errors, one saying that it expected ';' before account (after main is declared), and the second that account was not declared for cin >> account.num;

like image 432
Josh Avatar asked May 11 '26 14:05

Josh


2 Answers

The problem is not actually in your code: while C does require you to prefix your variables with struct in this case, C++ does not. The problem is actually that there is a global function on Unix named acct - it is this that is confusing the compiler. If you renamed your struct to something else, say bank_account, it will behave as you expected.

like image 115
Jack Lloyd Avatar answered May 14 '26 03:05

Jack Lloyd


If you change the "acct account;" in main to "struct acct account;" it should compile. You haven't actually declared a new typedef "acct" in your code, but Visual C++ helpfully does one for you as a non-standard extension. XCode is more strict.

An alternative fix is to do "typedef struct acct { ... } acct;" which will both declare the acct structure and create a new typedef.

like image 33
Berry Avatar answered May 14 '26 03:05

Berry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!