Conditionally set a variable if it's NULL

旧街凉风 提交于 2019-12-02 03:17:18

问题


When stepping through a sqlite3_stmt, I'd like to check against a return value of NULL rather than store it and check against the stored value.

Here's what I'm doing now:

char *email = (char *)sqlite3_column_text(statement, 10);
if (email == NULL) email = "";

And here is what I'd like to be doing, minus the double-call to column:

char *email = ((char *)sqlite3_column_text(statement, 10)) ? (char *)sqlite3_column_text(statement, 10) : "";

Is there some way to express the second expression more concisely? I have to do a lot of these repetitively, so I'm looking for brevity.

I know this is a problem of control flow rather than a problem with the SQLite API itself but there you have it. I can't think of a good way to do this.


回答1:


A GNU extension to C allows the ternary conditional operator to evaluate to its condition if it's true and there's nothing in the first branch:

char *email = (char *)sqlite3_column_text(statement, 10);
email = email ? : "";

or, more exactly what you say you're looking for

char * email = (char *)sqlite3_column_text(statement, 10) ? : "";

This works when compiling with Clang, too.

Another possibility would be:

char *email = (char *)sqlite3_column_text(statement, 10);
email = (NULL == email) ? email : "";

But I think I'd recommend just going with your first option. Make a code snippet if you're doing it a lot.




回答2:


Does this work?

char *email;
// Reviewed by "R." to verify sequence point correctness.
email = (email = (char *)sqlite3_column_text(statement, 10))? email : "";


来源:https://stackoverflow.com/questions/15121336/conditionally-set-a-variable-if-its-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!