tôi đã viết các chức năng tuyệt đối sử dụng nhà điều hành ternary như sautuyên bố trở lại trong ternary nhà điều hành C++
int abs(int a) {
a >=0 ? return a : return -a;
}
tôi nhận được thông báo lỗi sau
../src/templates.cpp: In function ‘int abs(int)’:
../src/templates.cpp:4: error: expected primary-expression before ‘return’
../src/templates.cpp:4: error: expected ‘:’ before ‘return’
../src/templates.cpp:4: error: expected primary-expression before ‘return’
../src/templates.cpp:4: error: expected ‘;’ before ‘return’
../src/templates.cpp:4: error: expected primary-expression before ‘:’ token
../src/templates.cpp:4: error: expected ‘;’ before ‘:’ token
../src/templates.cpp:5: warning: no return statement in function returning non-void
Nếu tôi viết như thế này
return a>=0 ? a : -a;
Tôi không nhận được bất kỳ lỗi nào. Sự khác biệt giữa hai yếu tố này là gì?
Đối số đầu tiên để các nhà điều hành ternary cũng là một biểu hiện, tất nhiên. Tuy nhiên, hai cái sau có thể là biểu thức của kiểu 'void'. –
Vâng, nó chỉ là vấn đề của OP là với hai cuối cùng ... –