Shradha
Shradha

Reputation: 1011

arguments in sqlite3_open()

I am using sqlite3 with iOS for the first time.. in the part where i have to open the connection to the database using the sqlite3_open(const char *filename, sqlite3 **ppDb) function. I was going through the following code snippet:

    int err = sqlite3_open((databasePath ? [databasePath fileSystemRepresentation] : ":memory:"), &db );
    if(err != SQLITE_OK) {
        NSLog(@"error opening!: %d", err);
        return NO;
    }

what is ? for and :memory:.. here, databasePath is an NSString that contains the path to the database and db is an instance of sqlite3.

Upvotes: 2

Views: 1127

Answers (2)

trojanfoe
trojanfoe

Reputation: 122391

?: is the ternary operator, explained here.

In this particular instance it's a shortcut way of writing:

int err;
if (databasePath) 
    err = sqlite3_open([databasePath fileSystemRepresentation], &db);
else
    err = sqlite3_open(":memory:", &db);
if (err != SQLITE_OK) {

But, as I'm sure you'll agree, much more concise.

Upvotes: 2

Raptor
Raptor

Reputation: 54242

? followed by : is called "Ternary operator".

The line (databasePath ? [databasePath fileSystemRepresentation] : ":memory:") means:

If databasePath is true, use [databasePath fileSystemRepresentation], else use ":memory:".

The line is the one-liner edition of the following:

if(databasePath) {
  return [databasePath fileSystemRepresentation];
} else {
  return ":memory:";
}

:memory: is In-Memory Database. See the docs for more information.

Upvotes: 0

Related Questions