Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Voidデータ型 | その他のデータ型と概念
C++データ型

bookVoidデータ型

メニューを表示するにはスワイプしてください

型を常に指定する必要があるのは、C++が静的型付け言語であるためです。コンパイラは各変数の正確な型を把握することで適切なメモリ領域を割り当て、型安全性を確保します。また、関数の戻り値やパラメータの型も認識する必要があります。

Note
注記

静的型付け言語とは、変数のデータ型が明示的に宣言され、コンパイラによって強制される言語のことです。

main.cpp

main.cpp

copy
12345678910
#include <iostream> // Let's consider a simple example. // Imagine you need to create a function that logs something in console. // What type should it return? ___ log(std::string message) { std::cout << message; return ___; }

この場合、特定の戻り値の型は必要ありません。intdoublefloat、またはboolであっても構いません。このシナリオでは、正確な型は重要ではありません。実際、何も返す必要がない場合はどうでしょうか。

関数の戻り値の型としてのvoid

何も返す必要がないように見える関数がよくあります。例えば:

main.cpp

main.cpp

copy
12345678
// Outputting information in console ___ log(std::string message) { std::cout << message; } // Updating values of variables ___ update(int& variable, int new_value) { variable = new_value; } // Calling another function ___ closeFile(std::fstream& file) { file.close(); }

この場合、voidデータ型を使用できます。プログラミングにおけるvoidデータ型は、値や型が存在しないことを示します。さまざまな用途がありますが、関数においては通常、関数が値を返さないことを示すために使用されます。

main.cpp

main.cpp

copy
123456789101112
#include <iostream> void log(std::string message) { std::cout << message; return; } int main() { log("This is a void function!"); }

注意

returnキーワードを使用しましたが、実際には値を渡していません。void関数ではreturnキーワード自体も省略できます。例で削除してみてください。

ポインタとしてのvoid

voidポインタ(void*)は、特定のデータ型に関連付けられていないポインタです。任意の型のオブジェクトを指すことができますが、使用する前に適切な型にキャストする必要があります。非常に便利ですが、時には理解が難しい場合もあります。

main.cpp

main.cpp

copy
1234567891011121314
#include <iostream> int main() { int num = 10; // Here we are creating a void pointer // Now it can point to any variable of any data type // You can try changing the type of `num` from `int` to `float` void* ptr = &num; // To use this pointer, we need to cast it to the appropriate type // VVV int* intPtr = static_cast<int*>(ptr); std::cout << *intPtr << std::endl; // Output: 10 }

この例では、ptrは整数(num)を指すvoidポインタです。その後、ptrをint*ポインタにキャストし、numの値にアクセスして出力します。

question mark

C++で関数の戻り値型としてvoidを使用することは何を意味しますか?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  3

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 4.  3
some-alt