そこで、XOR ビット演算子を使用して 2 つの数値を交換するマクロを作成しました。XOR ゲートを使用して数値を交換するアルゴリズムはよく知られています (つまり、a ^= b; b ^= a; a ^= b;) が、マクロを呼び出すときに構文エラーが発生し続けます。どこかにセミコロンが必要だと言っています。
正確なエラー:
Line 73: error C2146: syntax error : missing ';' before identifier 'a'
私のプログラムが問題を抱えているファイルは次のとおりです。
#define swapNumbers(x, y, z) z = x, x = y, y = z;
#define swapStrings(str1, str2, str3) str3 = str1, str1 = str2, str2 = str3;
#define swapUsingXOR (a, b) a = a ^ b, b = b ^ a, a = a ^ b;
#include <iostream>
#include "protocol.h"
#include <string>
void PrintMenu()
{
std::cout << "\n\nChapter 16 -- Learn By Doings " << std::endl;
std::cout << "\n1. Learn By Doing 16.4 " << std::endl;
std::cout << "2. Learn By Doing 16.5 " << std::endl;
std::cout << "3. Learn By Doing 16.6 " << std::endl;
std::cout << "4. Exit " << std::endl;
NewLine();
}
void GetMenuChoice(int &menuChoice)
{
std::cin >> menuChoice;
}
void ExecuteMenuChoice(int &menuChoice)
{
switch(menuChoice)
{
case 1:
{
//Learn By Doing 16.4
//Swap two numbers
int x = 10;
int y = 20;
int z = 30;
std::cout << "\nBefore swapping x is " << x << " and y is " << y << std::endl;
swapNumbers(x, y, z);
std::cout << "After swapping x is " << x << " and y is " << y << std::endl;
NewLine();
//Swap two cStrings
char * firstName = "Magnus";
char * lastName = "Carlsen";
char * tempName = "GOAT";
std::cout << "\nBefore swapping, first name is " << firstName << " and last name is " << lastName << std::endl;
swapStrings(firstName, lastName, tempName);
std::cout << "After swapping, first name is " << firstName << " and last name is " << lastName << std::endl;
}
break;
case 2:
//Learn By Doing 16.5
{
int x = 0;
//Check if number is power of two
std::cout << "\nEnter number: " << std::endl;
std::cin >> x;
NewLine();
std::cout << ChangeBoolToString(isPowerOfTwo(x));
//Swap numbers using bitwise operations
NewLine();
int a = 666;
int b = 777;
std::cout << "\n\nBefore swapping a is " << a << " and b is " << b << std::endl;
swapUsingXOR(a, b);
std::cout << "After swapping a is " << a << " and b is " << b << std::endl;
}
break;
case 3:
//Learn By Doing 16.6
break;
case 4:
//Exit
NewLine();
break;
default:
std::cout << "Invalid input. Please enter a number between 1 and 4. " << std::endl;
}
}
void NewLine()
{
std::cout << ' ' << std::endl;
}
bool isPowerOfTwo(int binaryNumber)
{
while(((binaryNumber & 1) == 0) && binaryNumber > 1)
binaryNumber >>= 1;
if(binaryNumber == 1)
return true;
else
return false;
}
char * ChangeBoolToString(bool function)
{
if(function == true)
return "Your number is a power of two! ";
else
return "Your number is not a power of two. ";
}